feat: Add tickets module and PayPal integration

Introduces a new 'Tickets' module for users to submit and manage issues within their condominium. This includes defining ticket types, statuses, priorities, and categories.

Additionally, this commit integrates PayPal as a payment option for family fee payments, enabling users to pay directly via PayPal using their client ID.

Key changes:
- Added `Ticket` related types and enums.
- Implemented `TicketService` functions for CRUD operations.
- Integrated `@paypal/react-paypal-js` library.
- Added `paypalClientId` to `AppSettings` and `Condo` types.
- Updated `FamilyDetail` page to include PayPal payment option.
- Added 'Segnalazioni' navigation link to `Layout`.
This commit is contained in:
2025-12-07 19:49:59 +01:00
parent 2566b406e1
commit 5311400615
14 changed files with 977 additions and 146 deletions

View File

@@ -4,6 +4,7 @@ import { useParams, useNavigate } from 'react-router-dom';
import { CondoService } from '../services/mockDb';
import { Family, Payment, AppSettings, MonthStatus, PaymentStatus, Condo } from '../types';
import { ArrowLeft, CheckCircle2, AlertCircle, Plus, Calendar, CreditCard, TrendingUp } from 'lucide-react';
import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js";
const MONTH_NAMES = [
"Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno",
@@ -26,6 +27,10 @@ export const FamilyDetail: React.FC = () => {
const [newPaymentMonth, setNewPaymentMonth] = useState<number>(new Date().getMonth() + 1);
const [newPaymentAmount, setNewPaymentAmount] = useState<number>(0);
const [isSubmitting, setIsSubmitting] = useState(false);
// Payment Method Selection
const [paymentMethod, setPaymentMethod] = useState<'manual' | 'paypal'>('manual');
const [paypalSuccessMsg, setPaypalSuccessMsg] = useState('');
useEffect(() => {
if (!id) return;
@@ -117,33 +122,45 @@ export const FamilyDetail: React.FC = () => {
return max > 0 ? Math.max(max * 1.2, baseline) : baseline;
}, [chartData, condo, family]);
const handleAddPayment = async (e: React.FormEvent) => {
e.preventDefault();
const handlePaymentSuccess = async (details?: any) => {
if (!family || !id) return;
setIsSubmitting(true);
try {
const payment = await CondoService.addPayment({
familyId: id,
amount: newPaymentAmount,
forMonth: newPaymentMonth,
forYear: selectedYear,
datePaid: new Date().toISOString()
});
const payment = await CondoService.addPayment({
familyId: id,
amount: newPaymentAmount,
forMonth: newPaymentMonth,
forYear: selectedYear,
datePaid: new Date().toISOString(),
notes: details ? `Pagato con PayPal (ID: ${details.id})` : ''
});
setPayments([...payments, payment]);
if (!availableYears.includes(selectedYear)) {
setAvailableYears([...availableYears, selectedYear].sort((a,b) => b-a));
}
setShowAddModal(false);
setPayments([...payments, payment]);
if (!availableYears.includes(selectedYear)) {
setAvailableYears([...availableYears, selectedYear].sort((a,b) => b-a));
}
if (details) {
setPaypalSuccessMsg("Pagamento riuscito!");
setTimeout(() => {
setShowAddModal(false);
setPaypalSuccessMsg("");
}, 2000);
} else {
setShowAddModal(false);
}
} catch (e) {
console.error("Failed to add payment", e);
console.error("Failed to add payment", e);
} finally {
setIsSubmitting(false);
setIsSubmitting(false);
}
};
const handleManualSubmit = (e: React.FormEvent) => {
e.preventDefault();
handlePaymentSuccess();
};
if (loading) return <div className="p-8 text-center text-slate-500">Caricamento dettagli...</div>;
if (!family) return <div className="p-8 text-center text-red-500">Famiglia non trovata.</div>;
@@ -184,7 +201,10 @@ export const FamilyDetail: React.FC = () => {
</select>
<button
onClick={() => setShowAddModal(true)}
onClick={() => {
setPaymentMethod(condo?.paypalClientId ? 'paypal' : 'manual');
setShowAddModal(true);
}}
className="flex-1 md:flex-none flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2.5 rounded-lg shadow-sm font-medium transition-all active:scale-95 whitespace-nowrap"
>
<Plus className="w-5 h-5" />
@@ -285,6 +305,7 @@ export const FamilyDetail: React.FC = () => {
<button
onClick={() => {
setNewPaymentMonth(month.monthIndex + 1);
setPaymentMethod(condo?.paypalClientId ? 'paypal' : 'manual');
setShowAddModal(true);
}}
className="ml-auto text-blue-600 hover:text-blue-800 text-xs font-bold uppercase tracking-wide px-2 py-1 rounded hover:bg-blue-50 transition-colors"
@@ -353,49 +374,117 @@ export const FamilyDetail: React.FC = () => {
<button onClick={() => setShowAddModal(false)} className="text-slate-400 hover:text-slate-600 w-8 h-8 flex items-center justify-center rounded-full hover:bg-slate-200"></button>
</div>
<form onSubmit={handleAddPayment} className="p-6 space-y-5">
<div>
<label className="block text-sm font-semibold text-slate-700 mb-1.5">Mese di Riferimento</label>
<select
value={newPaymentMonth}
onChange={(e) => setNewPaymentMonth(parseInt(e.target.value))}
className="w-full border border-slate-300 rounded-xl p-3 focus:ring-2 focus:ring-blue-500 outline-none bg-white"
>
{MONTH_NAMES.map((name, i) => (
<option key={i} value={i + 1}>{name}</option>
))}
</select>
</div>
<div className="p-6">
{/* Payment Method Switcher */}
{condo?.paypalClientId && (
<div className="flex bg-slate-100 rounded-lg p-1 mb-6">
<button
onClick={() => setPaymentMethod('manual')}
className={`flex-1 py-1.5 text-sm font-medium rounded-md transition-all ${paymentMethod === 'manual' ? 'bg-white text-slate-800 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
>
Manuale
</button>
<button
onClick={() => setPaymentMethod('paypal')}
className={`flex-1 py-1.5 text-sm font-medium rounded-md transition-all ${paymentMethod === 'paypal' ? 'bg-white text-blue-800 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
>
PayPal
</button>
</div>
)}
<div>
<label className="block text-sm font-semibold text-slate-700 mb-1.5">Importo ()</label>
<input
type="number"
step="0.01"
required
value={newPaymentAmount}
onChange={(e) => setNewPaymentAmount(parseFloat(e.target.value))}
className="w-full border border-slate-300 rounded-xl p-3 focus:ring-2 focus:ring-blue-500 outline-none text-lg font-medium"
/>
</div>
{paymentMethod === 'manual' ? (
<form onSubmit={handleManualSubmit} className="space-y-5">
<div>
<label className="block text-sm font-semibold text-slate-700 mb-1.5">Mese di Riferimento</label>
<select
value={newPaymentMonth}
onChange={(e) => setNewPaymentMonth(parseInt(e.target.value))}
className="w-full border border-slate-300 rounded-xl p-3 focus:ring-2 focus:ring-blue-500 outline-none bg-white"
>
{MONTH_NAMES.map((name, i) => (
<option key={i} value={i + 1}>{name}</option>
))}
</select>
</div>
<div className="pt-2 flex gap-3">
<button
type="button"
onClick={() => setShowAddModal(false)}
className="flex-1 px-4 py-3 border border-slate-300 text-slate-700 rounded-xl hover:bg-slate-50 font-bold text-sm"
>
Annulla
</button>
<button
type="submit"
disabled={isSubmitting}
className="flex-1 px-4 py-3 bg-blue-600 text-white rounded-xl hover:bg-blue-700 font-bold text-sm disabled:opacity-50"
>
{isSubmitting ? '...' : 'Conferma'}
</button>
</div>
</form>
<div>
<label className="block text-sm font-semibold text-slate-700 mb-1.5">Importo ()</label>
<input
type="number"
step="0.01"
required
value={newPaymentAmount}
onChange={(e) => setNewPaymentAmount(parseFloat(e.target.value))}
className="w-full border border-slate-300 rounded-xl p-3 focus:ring-2 focus:ring-blue-500 outline-none text-lg font-medium"
/>
</div>
<div className="pt-2 flex gap-3">
<button
type="button"
onClick={() => setShowAddModal(false)}
className="flex-1 px-4 py-3 border border-slate-300 text-slate-700 rounded-xl hover:bg-slate-50 font-bold text-sm"
>
Annulla
</button>
<button
type="submit"
disabled={isSubmitting}
className="flex-1 px-4 py-3 bg-blue-600 text-white rounded-xl hover:bg-blue-700 font-bold text-sm disabled:opacity-50"
>
{isSubmitting ? '...' : 'Conferma'}
</button>
</div>
</form>
) : (
<div className="space-y-6">
<div className="bg-blue-50 p-4 rounded-xl text-center">
<p className="text-sm text-slate-500 mb-1">Stai per pagare</p>
<p className="text-3xl font-bold text-blue-700"> {newPaymentAmount.toFixed(2)}</p>
<p className="text-sm font-medium text-slate-600 mt-1">{MONTH_NAMES[newPaymentMonth - 1]} {selectedYear}</p>
</div>
{paypalSuccessMsg ? (
<div className="bg-green-100 text-green-700 p-4 rounded-xl text-center font-bold flex items-center justify-center gap-2">
<CheckCircle2 className="w-5 h-5"/>
{paypalSuccessMsg}
</div>
) : (
<div className="min-h-[150px] flex items-center justify-center">
{condo?.paypalClientId && (
<PayPalScriptProvider options={{ clientId: condo.paypalClientId, currency: "EUR" }}>
<PayPalButtons
style={{ layout: "vertical" }}
createOrder={(data, actions) => {
return actions.order.create({
intent: "CAPTURE",
purchase_units: [
{
description: `Quota ${MONTH_NAMES[newPaymentMonth - 1]} ${selectedYear} - Famiglia ${family.name}`,
amount: {
currency_code: "EUR",
value: newPaymentAmount.toString(),
},
},
],
});
}}
onApprove={(data, actions) => {
if(!actions.order) return Promise.resolve();
return actions.order.capture().then((details) => {
handlePaymentSuccess(details);
});
}}
/>
</PayPalScriptProvider>
)}
</div>
)}
<p className="text-xs text-center text-slate-400">Il pagamento sarà registrato automaticamente.</p>
</div>
)}
</div>
</div>
</div>
)}

View File

@@ -2,7 +2,7 @@
import React, { useEffect, useState } from 'react';
import { CondoService } from '../services/mockDb';
import { AppSettings, Family, User, AlertDefinition, Condo, Notice, NoticeIconType, NoticeRead } from '../types';
import { Save, Building, Coins, Plus, Pencil, Trash2, X, CalendarCheck, AlertTriangle, User as UserIcon, Server, Bell, Clock, FileText, Lock, Megaphone, CheckCircle2, Info, Hammer, Link as LinkIcon, Eye, Calendar, List, UserCog, Mail, Power, MapPin } from 'lucide-react';
import { Save, Building, Coins, Plus, Pencil, Trash2, X, CalendarCheck, AlertTriangle, User as UserIcon, Server, Bell, Clock, FileText, Lock, Megaphone, CheckCircle2, Info, Hammer, Link as LinkIcon, Eye, Calendar, List, UserCog, Mail, Power, MapPin, CreditCard } from 'lucide-react';
export const SettingsPage: React.FC = () => {
const currentUser = CondoService.getCurrentUser();
@@ -40,6 +40,7 @@ export const SettingsPage: React.FC = () => {
province: '',
zipCode: '',
notes: '',
paypalClientId: '',
defaultMonthlyQuota: 100
});
@@ -235,7 +236,7 @@ export const SettingsPage: React.FC = () => {
// --- Condo Management Handlers ---
const openAddCondoModal = () => {
setEditingCondo(null);
setCondoForm({ name: '', address: '', streetNumber: '', city: '', province: '', zipCode: '', notes: '', defaultMonthlyQuota: 100 });
setCondoForm({ name: '', address: '', streetNumber: '', city: '', province: '', zipCode: '', notes: '', paypalClientId: '', defaultMonthlyQuota: 100 });
setShowCondoModal(true);
};
@@ -249,6 +250,7 @@ export const SettingsPage: React.FC = () => {
province: c.province || '',
zipCode: c.zipCode || '',
notes: c.notes || '',
paypalClientId: c.paypalClientId || '',
defaultMonthlyQuota: c.defaultMonthlyQuota
});
setShowCondoModal(true);
@@ -266,6 +268,7 @@ export const SettingsPage: React.FC = () => {
province: condoForm.province,
zipCode: condoForm.zipCode,
notes: condoForm.notes,
paypalClientId: condoForm.paypalClientId,
defaultMonthlyQuota: condoForm.defaultMonthlyQuota
};
@@ -607,6 +610,11 @@ export const SettingsPage: React.FC = () => {
</div>
)}
{/* Rest of the file (Families, Users, Notices, Alerts, SMTP Tabs) remains mostly same, just update modal */}
{/* ... (Existing Tabs Code for Families, Users, Notices, Alerts, SMTP) ... */}
{/* Only change is inside CONDO MODAL */}
{/* Families Tab */}
{isAdmin && activeTab === 'families' && (
<div className="space-y-4 animate-fade-in">
@@ -789,7 +797,7 @@ export const SettingsPage: React.FC = () => {
</div>
)}
{/* ALERT MODAL */}
{/* ALERT MODAL (Existing) */}
{showAlertModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-xl shadow-xl w-full max-w-md p-6 animate-in fade-in zoom-in duration-200">
@@ -826,7 +834,7 @@ export const SettingsPage: React.FC = () => {
</div>
)}
{/* NOTICE MODAL */}
{/* NOTICE MODAL (Existing) */}
{showNoticeModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-xl shadow-xl w-full max-w-lg p-6 animate-in fade-in zoom-in duration-200">
@@ -868,7 +876,7 @@ export const SettingsPage: React.FC = () => {
</div>
)}
{/* READ DETAILS MODAL */}
{/* READ DETAILS MODAL (Existing) */}
{showReadDetailsModal && selectedNoticeId && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-xl shadow-xl w-full max-w-md p-6 animate-in fade-in zoom-in duration-200">
@@ -907,7 +915,7 @@ export const SettingsPage: React.FC = () => {
</div>
)}
{/* USER MODAL */}
{/* USER MODAL (Existing) */}
{showUserModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-xl shadow-xl w-full max-w-md p-6 animate-in fade-in zoom-in duration-200">
@@ -950,10 +958,10 @@ export const SettingsPage: React.FC = () => {
</div>
)}
{/* CONDO MODAL */}
{/* CONDO MODAL (UPDATED) */}
{showCondoModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-xl shadow-xl w-full max-w-lg p-6 animate-in fade-in zoom-in duration-200">
<div className="bg-white rounded-xl shadow-xl w-full max-w-lg p-6 animate-in fade-in zoom-in duration-200 overflow-y-auto max-h-[90vh]">
<h3 className="font-bold text-lg mb-4 text-slate-800">{editingCondo ? 'Modifica Condominio' : 'Nuovo Condominio'}</h3>
<form onSubmit={handleCondoSubmit} className="space-y-4">
@@ -985,9 +993,27 @@ export const SettingsPage: React.FC = () => {
</div>
</div>
{/* PayPal Integration Section */}
<div className="bg-blue-50 p-3 rounded-lg border border-blue-100">
<div className="flex items-center gap-2 mb-2 text-blue-800">
<CreditCard className="w-4 h-4"/>
<span className="text-xs font-bold uppercase">Configurazione Pagamenti</span>
</div>
<div>
<label className="text-xs font-semibold text-slate-600 block mb-1">PayPal Client ID (REST API App)</label>
<input
className="w-full border p-2 rounded text-slate-700 text-sm"
placeholder="Es: Afg... (Ottienilo da developer.paypal.com)"
value={condoForm.paypalClientId}
onChange={e => setCondoForm({...condoForm, paypalClientId: e.target.value})}
/>
<p className="text-[10px] text-slate-500 mt-1">Necessario per abilitare i pagamenti online delle rate.</p>
</div>
</div>
{/* Notes */}
<div>
<textarea className="w-full border p-2.5 rounded-lg text-slate-700 h-20" placeholder="Note (opzionali)" value={condoForm.notes} onChange={e => setCondoForm({...condoForm, notes: e.target.value})} />
<textarea className="w-full border p-2.5 rounded-lg text-slate-700 h-16" placeholder="Note (opzionali)" value={condoForm.notes} onChange={e => setCondoForm({...condoForm, notes: e.target.value})} />
</div>
{/* Quota */}
@@ -1005,7 +1031,7 @@ export const SettingsPage: React.FC = () => {
</div>
)}
{/* FAMILY MODAL */}
{/* FAMILY MODAL (Existing) */}
{showFamilyModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-2xl shadow-xl w-full max-w-lg p-6">
@@ -1068,4 +1094,4 @@ export const SettingsPage: React.FC = () => {
)}
</div>
);
};
};

392
pages/Tickets.tsx Normal file
View File

@@ -0,0 +1,392 @@
import React, { useEffect, useState } from 'react';
import { CondoService } from '../services/mockDb';
import { Ticket, TicketStatus, TicketPriority, TicketCategory, TicketAttachment } from '../types';
import { MessageSquareWarning, Plus, Search, Filter, Paperclip, X, CheckCircle2, Clock, XCircle, FileIcon, Image as ImageIcon, Film } from 'lucide-react';
export const TicketsPage: React.FC = () => {
const user = CondoService.getCurrentUser();
const isAdmin = user?.role === 'admin' || user?.role === 'poweruser';
const [tickets, setTickets] = useState<Ticket[]>([]);
const [loading, setLoading] = useState(true);
const [filterStatus, setFilterStatus] = useState<string>('ALL');
const [showModal, setShowModal] = useState(false);
const [viewTicket, setViewTicket] = useState<Ticket | null>(null);
const [submitting, setSubmitting] = useState(false);
// Form State
const [formTitle, setFormTitle] = useState('');
const [formDesc, setFormDesc] = useState('');
const [formCategory, setFormCategory] = useState<TicketCategory>(TicketCategory.OTHER);
const [formPriority, setFormPriority] = useState<TicketPriority>(TicketPriority.MEDIUM);
const [attachments, setAttachments] = useState<{fileName: string, fileType: string, data: string}[]>([]);
// File Reading helper
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files.length > 0) {
const newAttachments = [];
for (let i = 0; i < e.target.files.length; i++) {
const file = e.target.files[i];
// Check size (e.g. 5MB limit per file for demo safety)
if (file.size > 5 * 1024 * 1024) {
alert(`Il file ${file.name} è troppo grande (max 5MB)`);
continue;
}
const base64 = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result as string);
reader.onerror = error => reject(error);
});
newAttachments.push({
fileName: file.name,
fileType: file.type,
data: base64
});
}
setAttachments([...attachments, ...newAttachments]);
}
};
const removeAttachment = (index: number) => {
const newAtt = [...attachments];
newAtt.splice(index, 1);
setAttachments(newAtt);
};
const loadTickets = async () => {
setLoading(true);
try {
const list = await CondoService.getTickets();
setTickets(list);
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
};
useEffect(() => {
loadTickets();
}, []);
const handleCreateSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setSubmitting(true);
try {
await CondoService.createTicket({
title: formTitle,
description: formDesc,
category: formCategory,
priority: formPriority,
attachments: attachments
});
setShowModal(false);
// Reset form
setFormTitle('');
setFormDesc('');
setAttachments([]);
loadTickets();
} catch (e) {
alert("Errore creazione ticket");
console.error(e);
} finally {
setSubmitting(false);
}
};
const handleStatusUpdate = async (status: TicketStatus) => {
if (!viewTicket) return;
try {
await CondoService.updateTicket(viewTicket.id, {
status: status,
priority: viewTicket.priority
});
// Update local state
const updated = { ...viewTicket, status };
setViewTicket(updated);
setTickets(tickets.map(t => t.id === updated.id ? updated : t));
} catch (e) { console.error(e); }
};
const handleDeleteTicket = async (id: string) => {
if (!confirm("Eliminare definitivamente questa segnalazione?")) return;
try {
await CondoService.deleteTicket(id);
setTickets(tickets.filter(t => t.id !== id));
setViewTicket(null);
} catch (e) { alert("Impossibile eliminare."); }
};
const filteredTickets = tickets.filter(t => filterStatus === 'ALL' || t.status === filterStatus);
// Helpers for Badge Colors
const getStatusColor = (s: TicketStatus) => {
switch(s) {
case TicketStatus.OPEN: return 'bg-blue-100 text-blue-700';
case TicketStatus.IN_PROGRESS: return 'bg-yellow-100 text-yellow-700';
case TicketStatus.RESOLVED: return 'bg-green-100 text-green-700';
case TicketStatus.CLOSED: return 'bg-slate-200 text-slate-600';
}
};
const getPriorityColor = (p: TicketPriority) => {
switch(p) {
case TicketPriority.LOW: return 'bg-slate-100 text-slate-600';
case TicketPriority.MEDIUM: return 'bg-blue-50 text-blue-600';
case TicketPriority.HIGH: return 'bg-orange-100 text-orange-600';
case TicketPriority.URGENT: return 'bg-red-100 text-red-600';
}
};
const getCategoryLabel = (c: TicketCategory) => {
switch(c) {
case TicketCategory.MAINTENANCE: return 'Manutenzione';
case TicketCategory.ADMINISTRATIVE: return 'Amministrazione';
case TicketCategory.CLEANING: return 'Pulizie';
case TicketCategory.NOISE: return 'Disturbo';
default: return 'Altro';
}
};
const openAttachment = async (ticketId: string, attId: string) => {
try {
const file = await CondoService.getTicketAttachment(ticketId, attId);
// Open base64 in new tab
const win = window.open();
if (win) {
// Determine display method
if (file.fileType.startsWith('image/')) {
win.document.write(`<img src="${file.data}" style="max-width:100%"/>`);
} else if (file.fileType === 'application/pdf') {
win.document.write(`<iframe src="${file.data}" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>`);
} else {
// Download link fallback
win.document.write(`<a href="${file.data}" download="${file.fileName}">Clicca qui per scaricare ${file.fileName}</a>`);
}
}
} catch (e) { alert("Errore apertura file"); }
};
return (
<div className="space-y-6 pb-20">
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
<div>
<h2 className="text-2xl font-bold text-slate-800">Segnalazioni</h2>
<p className="text-slate-500">Gestisci guasti e richieste</p>
</div>
<button
onClick={() => setShowModal(true)}
className="bg-blue-600 text-white px-4 py-2 rounded-lg font-medium flex items-center gap-2 hover:bg-blue-700 transition-colors"
>
<Plus className="w-5 h-5"/> Nuova Segnalazione
</button>
</div>
{/* Filters */}
<div className="flex gap-2 overflow-x-auto pb-2 no-scrollbar">
{['ALL', 'OPEN', 'IN_PROGRESS', 'RESOLVED', 'CLOSED'].map(status => (
<button
key={status}
onClick={() => setFilterStatus(status)}
className={`px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap ${filterStatus === status ? 'bg-slate-800 text-white' : 'bg-white border border-slate-200 text-slate-600 hover:bg-slate-50'}`}
>
{status === 'ALL' ? 'Tutti' : status === 'OPEN' ? 'Aperti' : status === 'IN_PROGRESS' ? 'In Corso' : status === 'RESOLVED' ? 'Risolti' : 'Chiusi'}
</button>
))}
</div>
{/* List */}
{loading ? (
<div className="text-center p-12 text-slate-400">Caricamento...</div>
) : filteredTickets.length === 0 ? (
<div className="text-center p-12 bg-white rounded-xl border border-dashed border-slate-300">
<MessageSquareWarning className="w-12 h-12 text-slate-300 mx-auto mb-3"/>
<p className="text-slate-500">Nessuna segnalazione trovata.</p>
</div>
) : (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{filteredTickets.map(ticket => (
<div key={ticket.id} onClick={() => setViewTicket(ticket)} className="bg-white p-5 rounded-xl border border-slate-200 shadow-sm hover:shadow-md transition-shadow cursor-pointer relative group">
<div className="flex justify-between items-start mb-3">
<span className={`text-[10px] font-bold px-2 py-1 rounded uppercase ${getStatusColor(ticket.status)}`}>
{ticket.status.replace('_', ' ')}
</span>
<span className={`text-[10px] font-bold px-2 py-1 rounded uppercase ${getPriorityColor(ticket.priority)}`}>
{ticket.priority}
</span>
</div>
<h3 className="font-bold text-slate-800 mb-1 line-clamp-1">{ticket.title}</h3>
<p className="text-xs text-slate-400 mb-3">{new Date(ticket.createdAt).toLocaleDateString()} {getCategoryLabel(ticket.category)}</p>
<p className="text-sm text-slate-600 line-clamp-3 mb-4">{ticket.description}</p>
<div className="flex items-center justify-between border-t border-slate-100 pt-3">
<div className="flex items-center gap-2 text-xs text-slate-500">
<div className="w-6 h-6 rounded-full bg-slate-200 flex items-center justify-center font-bold text-slate-600">
{ticket.userName ? ticket.userName.charAt(0) : '?'}
</div>
<span className="truncate max-w-[100px]">{ticket.userName || 'Utente'}</span>
</div>
{ticket.attachments && ticket.attachments.length > 0 && (
<div className="flex items-center gap-1 text-xs text-blue-600 font-medium">
<Paperclip className="w-3 h-3"/> {ticket.attachments.length}
</div>
)}
</div>
</div>
))}
</div>
)}
{/* CREATE MODAL */}
{showModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-xl shadow-xl w-full max-w-lg p-6 animate-in fade-in zoom-in duration-200 max-h-[90vh] overflow-y-auto">
<div className="flex justify-between items-center mb-6">
<h3 className="font-bold text-lg text-slate-800">Nuova Segnalazione</h3>
<button onClick={() => setShowModal(false)}><X className="w-6 h-6 text-slate-400"/></button>
</div>
<form onSubmit={handleCreateSubmit} className="space-y-4">
<div>
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Oggetto</label>
<input className="w-full border p-2.5 rounded-lg text-slate-700" value={formTitle} onChange={e => setFormTitle(e.target.value)} required placeholder="Es. Luce scale rotta" />
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Categoria</label>
<select className="w-full border p-2.5 rounded-lg text-slate-700 bg-white" value={formCategory} onChange={e => setFormCategory(e.target.value as any)}>
<option value={TicketCategory.MAINTENANCE}>Manutenzione</option>
<option value={TicketCategory.ADMINISTRATIVE}>Amministrazione</option>
<option value={TicketCategory.CLEANING}>Pulizie</option>
<option value={TicketCategory.NOISE}>Rumori</option>
<option value={TicketCategory.OTHER}>Altro</option>
</select>
</div>
<div>
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Priorità</label>
<select className="w-full border p-2.5 rounded-lg text-slate-700 bg-white" value={formPriority} onChange={e => setFormPriority(e.target.value as any)}>
<option value={TicketPriority.LOW}>Bassa</option>
<option value={TicketPriority.MEDIUM}>Media</option>
<option value={TicketPriority.HIGH}>Alta</option>
<option value={TicketPriority.URGENT}>Urgente</option>
</select>
</div>
</div>
<div>
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Descrizione</label>
<textarea className="w-full border p-2.5 rounded-lg text-slate-700 h-24" value={formDesc} onChange={e => setFormDesc(e.target.value)} required placeholder="Dettagli del problema..." />
</div>
<div>
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Allegati (Foto, Video, PDF)</label>
<div className="border-2 border-dashed border-slate-300 rounded-lg p-4 text-center hover:bg-slate-50 transition-colors relative">
<input type="file" multiple onChange={handleFileChange} className="absolute inset-0 opacity-0 cursor-pointer" accept="image/*,video/*,application/pdf" />
<div className="flex flex-col items-center gap-1">
<Paperclip className="w-6 h-6 text-slate-400"/>
<span className="text-sm text-slate-500">Clicca o trascina file qui</span>
<span className="text-[10px] text-slate-400">Max 5MB per file</span>
</div>
</div>
{attachments.length > 0 && (
<div className="mt-3 space-y-2">
{attachments.map((att, idx) => (
<div key={idx} className="flex items-center justify-between bg-slate-50 p-2 rounded border border-slate-200">
<div className="flex items-center gap-2 truncate">
{att.fileType.includes('image') ? <ImageIcon className="w-4 h-4 text-blue-500"/> : att.fileType.includes('video') ? <Film className="w-4 h-4 text-purple-500"/> : <FileIcon className="w-4 h-4 text-slate-500"/>}
<span className="text-xs truncate max-w-[200px]">{att.fileName}</span>
</div>
<button type="button" onClick={() => removeAttachment(idx)} className="text-red-500 hover:bg-red-50 p-1 rounded"><X className="w-4 h-4"/></button>
</div>
))}
</div>
)}
</div>
<div className="pt-2">
<button type="submit" disabled={submitting} className="w-full bg-blue-600 text-white py-3 rounded-lg font-bold hover:bg-blue-700 transition-colors flex justify-center items-center gap-2">
{submitting ? 'Invio in corso...' : 'Invia Segnalazione'}
</button>
</div>
</form>
</div>
</div>
)}
{/* VIEW DETAILS MODAL */}
{viewTicket && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-xl shadow-xl w-full max-w-2xl p-6 animate-in fade-in zoom-in duration-200 max-h-[90vh] overflow-y-auto">
<div className="flex justify-between items-start mb-4">
<div>
<h3 className="font-bold text-xl text-slate-800">{viewTicket.title}</h3>
<p className="text-sm text-slate-500">{new Date(viewTicket.createdAt).toLocaleString()} {getCategoryLabel(viewTicket.category)}</p>
</div>
<button onClick={() => setViewTicket(null)}><X className="w-6 h-6 text-slate-400 hover:text-slate-600"/></button>
</div>
<div className="flex gap-2 mb-6">
<div className={`px-3 py-1 rounded-lg text-sm font-bold uppercase ${getStatusColor(viewTicket.status)}`}>
{viewTicket.status.replace('_', ' ')}
</div>
<div className={`px-3 py-1 rounded-lg text-sm font-bold uppercase ${getPriorityColor(viewTicket.priority)}`}>
{viewTicket.priority}
</div>
</div>
<div className="bg-slate-50 p-4 rounded-xl border border-slate-200 mb-6 text-slate-700 whitespace-pre-wrap leading-relaxed">
{viewTicket.description}
</div>
{/* Attachments */}
{viewTicket.attachments && viewTicket.attachments.length > 0 && (
<div className="mb-6">
<h4 className="font-bold text-sm text-slate-800 mb-2 flex items-center gap-2"><Paperclip className="w-4 h-4"/> Allegati</h4>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
{viewTicket.attachments.map(att => (
<button
key={att.id}
onClick={() => openAttachment(viewTicket.id, att.id)}
className="flex flex-col items-center justify-center p-3 bg-white border border-slate-200 rounded-lg hover:border-blue-400 hover:shadow-sm transition-all text-center"
>
{att.fileType.includes('image') ? <ImageIcon className="w-6 h-6 text-blue-500 mb-1"/> : att.fileType.includes('video') ? <Film className="w-6 h-6 text-purple-500 mb-1"/> : <FileIcon className="w-6 h-6 text-slate-500 mb-1"/>}
<span className="text-[10px] text-slate-600 truncate w-full">{att.fileName}</span>
</button>
))}
</div>
</div>
)}
{/* Admin Actions */}
{isAdmin && (
<div className="border-t border-slate-100 pt-4">
<h4 className="font-bold text-sm text-slate-500 uppercase mb-3">Gestione Admin</h4>
<div className="flex flex-wrap gap-2">
{viewTicket.status !== TicketStatus.IN_PROGRESS && (
<button onClick={() => handleStatusUpdate(TicketStatus.IN_PROGRESS)} className="px-4 py-2 bg-yellow-100 text-yellow-700 rounded-lg font-bold text-sm hover:bg-yellow-200">Prendi in Carico</button>
)}
{viewTicket.status !== TicketStatus.RESOLVED && (
<button onClick={() => handleStatusUpdate(TicketStatus.RESOLVED)} className="px-4 py-2 bg-green-100 text-green-700 rounded-lg font-bold text-sm hover:bg-green-200">Segna Risolto</button>
)}
{viewTicket.status !== TicketStatus.CLOSED && (
<button onClick={() => handleStatusUpdate(TicketStatus.CLOSED)} className="px-4 py-2 bg-slate-200 text-slate-700 rounded-lg font-bold text-sm hover:bg-slate-300">Chiudi</button>
)}
<button onClick={() => handleDeleteTicket(viewTicket.id)} className="ml-auto px-4 py-2 text-red-600 font-medium text-sm hover:bg-red-50 rounded-lg">Elimina</button>
</div>
</div>
)}
{!isAdmin && viewTicket.status === TicketStatus.OPEN && (
<div className="border-t border-slate-100 pt-4 flex justify-end">
<button onClick={() => handleDeleteTicket(viewTicket.id)} className="px-4 py-2 text-red-600 font-medium text-sm hover:bg-red-50 rounded-lg">Elimina Segnalazione</button>
</div>
)}
</div>
</div>
)}
</div>
);
};