import React, { useState } from 'react';
import { IHSEIncident } from '../../types';
import { Activity, X, Edit, Trash2 } from 'lucide-react';
import { dataService } from '../../services/dataService';
import { hseIncidentStatusVi, hseSeverityVi } from '../../utils/displayVi';

interface HSEIncidentsProps {
    incidents: IHSEIncident[];
    selectedProjectId: string | null;
    onRefresh: () => void;
}

const HSEIncidents: React.FC<HSEIncidentsProps> = ({ incidents, selectedProjectId, onRefresh }) => {
    const [isIncidentModalOpen, setIsIncidentModalOpen] = useState(false);
    const [editingIncidentId, setEditingIncidentId] = useState<string | null>(null);
    const [incidentForm, setIncidentForm] = useState<{
        date: string;
        type: string;
        description: string;
        severity: 'Low' | 'Medium' | 'High' | 'Critical';
        mitigationAction: string;
        status: 'Open' | 'Closed';
    }>({
        date: '',
        type: 'Tai nạn lao động',
        description: '',
        severity: 'Low',
        mitigationAction: '',
        status: 'Open'
    });

    const handleCreateOrUpdateIncident = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!selectedProjectId) return;
        try {
            if (editingIncidentId) {
                await dataService.updateHSEIncident(editingIncidentId, {
                    ...incidentForm,
                    siteId: selectedProjectId
                });
            } else {
                await dataService.createHSEIncident({
                    ...incidentForm,
                    siteId: selectedProjectId
                });
            }

            setIsIncidentModalOpen(false);
            setEditingIncidentId(null);
            resetForm();
            onRefresh();
        } catch (error) {
            console.error('Failed to save incident:', error);
            alert('Không thể lưu báo cáo sự cố. Vui lòng thử lại.');
        }
    };

    const resetForm = () => {
        setIncidentForm({
            date: '',
            type: 'Tai nạn lao động',
            description: '',
            severity: 'Low',
            mitigationAction: '',
            status: 'Open'
        });
    };

    const handleEditIncident = (incident: IHSEIncident) => {
        setIncidentForm({
            date: new Date(incident.date).toISOString().split('T')[0],
            type: incident.type,
            description: incident.description,
            severity: incident.severity as any,
            mitigationAction: incident.mitigationAction || '',
            status: incident.status as any
        });
        setEditingIncidentId(incident._id);
        setIsIncidentModalOpen(true);
    };

    const handleDeleteIncident = async (id: string) => {
        if (!confirm('Bạn có chắc chắn muốn xóa sự cố này không?')) return;
        try {
            await dataService.deleteHSEIncident(id);
            onRefresh();
        } catch (error) {
            console.error('Failed to delete incident:', error);
            alert('Không thể xóa sự cố. Vui lòng thử lại.');
        }
    };

    return (
        <div>
            <div className="p-4 border-b border-slate-100 dark:border-slate-700 flex justify-between items-center bg-slate-50 dark:bg-slate-800/50">
                <h3 className="font-bold text-slate-700 dark:text-slate-200">Nhật ký sự cố & An toàn</h3>
                <button
                    onClick={() => {
                        setEditingIncidentId(null);
                        resetForm();
                        setIsIncidentModalOpen(true);
                    }}
                    className="px-3 py-1 bg-red-600 text-white text-xs rounded hover:bg-red-700"
                >
                    Báo cáo sự cố
                </button>
            </div>
            <div className="overflow-x-auto">
                {incidents.length === 0 ? (
                    <div className="p-12 text-center flex flex-col items-center justify-center">
                        <div className="bg-slate-100 dark:bg-slate-700 p-4 rounded-full mb-3">
                            <Activity size={32} className="text-slate-400 dark:text-slate-500" />
                        </div>
                        <h4 className="text-lg font-medium text-slate-700 dark:text-slate-300">Chưa có sự cố nào</h4>
                        <p className="text-slate-500 dark:text-slate-400 text-sm mt-1 max-w-xs mx-auto">
                            Hệ thống chưa ghi nhận sự cố an toàn nào cho dự án này.
                        </p>
                    </div>
                ) : (
                    <table className="min-w-full divide-y divide-slate-200 dark:divide-slate-700">
                        <thead className="bg-slate-50 dark:bg-slate-700/50">
                            <tr>
                                <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase whitespace-nowrap">Ngày</th>
                                <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase whitespace-nowrap">Loại</th>
                                <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase min-w-[200px]">Mô tả</th>
                                <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase whitespace-nowrap">Mức độ</th>
                                <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase whitespace-nowrap">Trạng thái</th>
                                <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase min-w-[200px]">Biện pháp khắc phục</th>
                                <th className="px-6 py-3 text-right text-xs font-medium text-slate-500 dark:text-slate-400 uppercase whitespace-nowrap">Hành động</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-200 dark:divide-slate-700">
                            {incidents.map(inc => (
                                <tr key={inc._id} className="hover:bg-slate-50 dark:hover:bg-slate-700/50">
                                    <td className="px-6 py-4 text-sm text-slate-500 dark:text-slate-400 whitespace-nowrap">{new Date(inc.date).toLocaleDateString('vi-VN')}</td>
                                    <td className="px-6 py-4 text-sm font-medium text-slate-900 dark:text-white whitespace-nowrap">{inc.type}</td>
                                    <td className="px-6 py-4 text-sm text-slate-600 dark:text-slate-300">{inc.description}</td>
                                    <td className="px-6 py-4 whitespace-nowrap">
                                        <span className={`px-2.5 py-1 text-xs font-bold rounded-full ${inc.severity === 'Critical' ? 'bg-red-100 dark:bg-red-900/40 text-red-800 dark:text-red-200 border border-red-200 dark:border-red-800' :
                                            inc.severity === 'High' ? 'bg-orange-100 dark:bg-orange-900/40 text-orange-800 dark:text-orange-200 border border-orange-200 dark:border-orange-800' :
                                                inc.severity === 'Medium' ? 'bg-yellow-100 dark:bg-yellow-900/40 text-yellow-800 dark:text-yellow-200 border border-yellow-200 dark:border-yellow-800' :
                                                    'bg-slate-100 dark:bg-slate-700 text-slate-800 dark:text-slate-300 border border-slate-200 dark:border-slate-600'
                                            }`}>
                                            {hseSeverityVi(String(inc.severity))}
                                        </span>
                                    </td>
                                    <td className="px-6 py-4 whitespace-nowrap">
                                        <span className={`px-2.5 py-1 inline-flex text-xs font-semibold rounded-full ${inc.status === 'Open' ? 'bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 border border-red-200 dark:border-red-800' : 'bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300 border border-green-200 dark:border-green-800'
                                            }`}>
                                            {hseIncidentStatusVi(String(inc.status))}
                                        </span>
                                    </td>
                                    <td className="px-6 py-4 text-sm text-slate-500 dark:text-slate-400 italic relative group">
                                        <div className="truncate max-w-[200px]">
                                            {inc.mitigationAction || '---'}
                                        </div>
                                        {inc.mitigationAction && inc.mitigationAction.length > 30 && (
                                            <div className="absolute hidden group-hover:block z-10 bg-black/80 text-white text-xs rounded p-2 min-w-[200px] left-0 top-full mt-1 shadow-lg whitespace-normal">
                                                {inc.mitigationAction}
                                            </div>
                                        )}
                                    </td>
                                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                        <button
                                            onClick={() => handleEditIncident(inc)}
                                            className="text-blue-600 hover:text-blue-900 dark:hover:text-blue-400 mr-2"
                                            title="Sửa"
                                        >
                                            <Edit size={16} />
                                        </button>
                                        <button
                                            onClick={() => handleDeleteIncident(inc._id)}
                                            className="text-red-600 hover:text-red-900 dark:hover:text-red-400"
                                            title="Xóa"
                                        >
                                            <Trash2 size={16} />
                                        </button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                )}
            </div>

            {/* Add/Edit Incident Modal */}
            {isIncidentModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
                    <div className="bg-white dark:bg-slate-800 rounded-xl shadow-xl w-full max-w-lg overflow-hidden">
                        <div className="p-4 border-b border-slate-200 dark:border-slate-700 flex justify-between items-center">
                            <h3 className="font-bold text-lg text-slate-800 dark:text-white">{editingIncidentId ? 'Cập nhật sự cố' : 'Báo cáo sự cố an toàn'}</h3>
                            <button onClick={() => setIsIncidentModalOpen(false)} className="text-slate-500 hover:text-slate-700 dark:hover:text-slate-300">
                                <X size={20} />
                            </button>
                        </div>
                        <form onSubmit={handleCreateOrUpdateIncident} className="p-6 space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Ngày xảy ra <span className="text-red-500">*</span></label>
                                <input
                                    type="date"
                                    required
                                    className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                    value={incidentForm.date}
                                    onChange={e => setIncidentForm({ ...incidentForm, date: e.target.value })}
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Loại sự cố</label>
                                <select
                                    className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                    value={incidentForm.type}
                                    onChange={e => setIncidentForm({ ...incidentForm, type: e.target.value })}
                                >
                                    <option value="Tai nạn lao động">Tai nạn lao động</option>
                                    <option value="Sự cố môi trường">Sự cố môi trường</option>
                                    <option value="Sự cố thiết bị">Sự cố thiết bị</option>
                                    <option value="Vi phạm quy trình">Vi phạm quy trình</option>
                                    <option value="Khác">Khác</option>
                                </select>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Mô tả chi tiết <span className="text-red-500">*</span></label>
                                <textarea
                                    required
                                    rows={3}
                                    className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                    value={incidentForm.description}
                                    onChange={e => setIncidentForm({ ...incidentForm, description: e.target.value })}
                                    placeholder="Mô tả sự việc đã xảy ra..."
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Mức độ nghiêm trọng</label>
                                <select
                                    className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                    value={incidentForm.severity}
                                    onChange={e => setIncidentForm({ ...incidentForm, severity: e.target.value as any })}
                                >
                                    <option value="Low">Thấp (Low)</option>
                                    <option value="Medium">Trung bình (Medium)</option>
                                    <option value="High">Cao (High)</option>
                                    <option value="Critical">Nghiêm trọng (Critical)</option>
                                </select>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Biện pháp khắc phục</label>
                                <textarea
                                    rows={2}
                                    className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                    value={incidentForm.mitigationAction}
                                    onChange={e => setIncidentForm({ ...incidentForm, mitigationAction: e.target.value })}
                                    placeholder="Đã thực hiện hành động gì..."
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Trạng thái xử lý</label>
                                <select
                                    className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                    value={incidentForm.status}
                                    onChange={e => setIncidentForm({ ...incidentForm, status: e.target.value as any })}
                                >
                                    <option value="Open">Đang xử lý (Open)</option>
                                    <option value="Closed">Đã giải quyết (Closed)</option>
                                </select>
                            </div>

                            <div className="flex justify-end gap-3 mt-6 pt-4 border-t border-slate-100 dark:border-slate-700">
                                <button
                                    type="button"
                                    onClick={() => setIsIncidentModalOpen(false)}
                                    className="px-4 py-2 text-sm font-medium text-slate-700 dark:text-slate-300 bg-white dark:bg-slate-700 border border-slate-300 dark:border-slate-600 rounded-lg hover:bg-slate-50 dark:hover:bg-slate-600"
                                >
                                    Hủy bỏ
                                </button>
                                <button
                                    type="submit"
                                    className="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 shadow-sm shadow-red-500/30"
                                >
                                    {editingIncidentId ? 'Cập nhật' : 'Lưu báo cáo'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default HSEIncidents;
