import React, { useState } from 'react';
import { IComplianceDoc } from '../../types';
import { ExternalLink, Edit, Trash2, X } from 'lucide-react';
import { dataService } from '../../services/dataService';

interface ComplianceDocumentsProps {
    docs: IComplianceDoc[];
    selectedProjectId: string | null;
    onRefresh: () => void;
}

const ComplianceDocuments: React.FC<ComplianceDocumentsProps> = ({ docs, selectedProjectId, onRefresh }) => {
    const [isAddModalOpen, setIsAddModalOpen] = useState(false);
    const [editingDocId, setEditingDocId] = useState<string | null>(null);
    const [formData, setFormData] = useState({
        name: '',
        type: 'Giấy phép',
        issuingAuthority: '',
        issueDate: '',
        expiryDate: '',
        status: 'Valid' as 'Valid' | 'Expiring Soon' | 'Expired',
        documentUrl: ''
    });

    const handleAddDoc = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
            if (!selectedProjectId) return;

            if (editingDocId) {
                await dataService.updateComplianceDoc(editingDocId, {
                    ...formData,
                    siteId: selectedProjectId
                });
            } else {
                await dataService.createComplianceDoc({
                    ...formData,
                    siteId: selectedProjectId
                });
            }

            setIsAddModalOpen(false);
            setEditingDocId(null);
            setFormData({
                name: '',
                type: 'Giấy phép',
                issuingAuthority: '',
                issueDate: '',
                expiryDate: '',
                status: 'Valid',
                documentUrl: ''
            });
            await onRefresh();
        } catch (error) {
            console.error('Failed to create doc:', error);
            alert('Không thể thêm văn bản. Vui lòng thử lại.');
        }
    };

    const handleEditDoc = (doc: IComplianceDoc) => {
        setFormData({
            name: doc.name,
            type: doc.type,
            issuingAuthority: doc.issuingAuthority,
            issueDate: doc.issueDate ? new Date(doc.issueDate).toISOString().split('T')[0] : '',
            expiryDate: doc.expiryDate ? new Date(doc.expiryDate).toISOString().split('T')[0] : '',
            status: doc.status as any,
            documentUrl: doc.documentUrl || ''
        });
        setEditingDocId(doc._id);
        setIsAddModalOpen(true);
    };

    const handleDeleteDoc = async (id: string) => {
        if (!confirm('Bạn có chắc chắn muốn xóa văn bản này không?')) return;
        try {
            await dataService.deleteComplianceDoc(id);
            await onRefresh();
        } catch (error) {
            console.error('Failed to delete doc:', error);
            alert('Không thể xóa văn bản. 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">Danh sách Giấy phép & Chứng chỉ</h3>
                <button
                    onClick={() => {
                        setFormData({
                            name: '',
                            type: 'Giấy phép',
                            issuingAuthority: '',
                            issueDate: '',
                            expiryDate: '',
                            status: 'Valid',
                            documentUrl: ''
                        });
                        setEditingDocId(null);
                        setIsAddModalOpen(true);
                    }}
                    className="px-3 py-1 bg-blue-600 text-white text-xs rounded hover:bg-blue-700 flex items-center gap-1"
                >
                    + Thêm văn bản
                </button>
            </div>
            <div className="overflow-x-auto">
                <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">Tên văn bản</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 whitespace-nowrap">Cơ quan cấp</th>
                            <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase whitespace-nowrap">Ngày hết hạn</th>
                            <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase whitespace-nowrap">File</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>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-200 dark:divide-slate-700">
                        {docs.map(doc => (
                            <tr key={doc._id} className="hover:bg-slate-50 dark:hover:bg-slate-700/50">
                                <td className="px-6 py-4 text-sm font-medium text-slate-900 dark:text-white min-w-[200px]">{doc.name}</td>
                                <td className="px-6 py-4 text-sm text-slate-500 dark:text-slate-400 whitespace-nowrap">{doc.type}</td>
                                <td className="px-6 py-4 text-sm text-slate-500 dark:text-slate-400 min-w-[150px]">{doc.issuingAuthority}</td>
                                <td className="px-6 py-4 text-sm text-slate-500 dark:text-slate-400 whitespace-nowrap">{new Date(doc.expiryDate).toLocaleDateString('vi-VN')}</td>
                                <td className="px-6 py-4 whitespace-nowrap">
                                    {doc.documentUrl ? (
                                        <a href={doc.documentUrl} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300">
                                            <ExternalLink size={18} />
                                        </a>
                                    ) : (
                                        <span className="text-slate-400 text-xs italic">N/A</span>
                                    )}
                                </td>
                                <td className="px-6 py-4 whitespace-nowrap">
                                    <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${doc.status === 'Valid' ? 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300' :
                                        doc.status === 'Expiring Soon' ? 'bg-orange-100 dark:bg-orange-900/30 text-orange-800 dark:text-orange-300' : 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-300'
                                        }`}>
                                        {doc.status === 'Valid' ? 'Hợp lệ' : doc.status === 'Expiring Soon' ? 'Sắp hết hạn' : 'Hết hạn'}
                                    </span>
                                </td>
                                <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                    <button
                                        onClick={() => handleEditDoc(doc)}
                                        className="text-blue-600 hover:text-blue-900 dark:hover:text-blue-400 mr-2"
                                        title="Sửa"
                                    >
                                        <Edit size={16} />
                                    </button>
                                    <button
                                        onClick={() => handleDeleteDoc(doc._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 Document Modal */}
            {isAddModalOpen && (
                <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">{editingDocId ? 'Cập nhật văn bản' : 'Thêm văn bản mới'}</h3>
                            <button onClick={() => { setIsAddModalOpen(false); setEditingDocId(null); }} className="text-slate-500 hover:text-slate-700 dark:hover:text-slate-300">
                                <X size={20} />
                            </button>
                        </div>
                        <form onSubmit={handleAddDoc} className="p-6 space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Tên văn bản <span className="text-red-500">*</span></label>
                                <input
                                    type="text"
                                    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={formData.name}
                                    onChange={e => setFormData({ ...formData, name: e.target.value })}
                                    placeholder="Nhập tên văn bản..."
                                />
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Loại văn bản</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={formData.type}
                                        onChange={e => setFormData({ ...formData, type: e.target.value })}
                                    >
                                        <option value="Giấy phép">Giấy phép</option>
                                        <option value="Chứng chỉ">Chứng chỉ</option>
                                        <option value="Báo cáo">Báo cáo</option>
                                        <option value="Quyết định">Quyết định</option>
                                        <option value="Hợp đồng">Hợp đồng</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">Cơ quan cấp</label>
                                    <input
                                        type="text"
                                        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={formData.issuingAuthority}
                                        onChange={e => setFormData({ ...formData, issuingAuthority: e.target.value })}
                                        placeholder="VD: Sở Công Thương"
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Ngày cấp</label>
                                    <input
                                        type="date"
                                        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={formData.issueDate}
                                        onChange={e => setFormData({ ...formData, issueDate: e.target.value })}
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Ngày hết hạn</label>
                                    <input
                                        type="date"
                                        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={formData.expiryDate}
                                        onChange={e => setFormData({ ...formData, expiryDate: e.target.value })}
                                    />
                                </div>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Link văn bản (URL)</label>
                                <input
                                    type="url"
                                    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={formData.documentUrl}
                                    onChange={e => setFormData({ ...formData, documentUrl: e.target.value })}
                                    placeholder="https://example.com/file.pdf"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Trạng thái</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={formData.status}
                                    onChange={e => setFormData({ ...formData, status: e.target.value as any })}
                                >
                                    <option value="Valid">Hợp lệ (Valid)</option>
                                    <option value="Expiring Soon">Sắp hết hạn (Expiring Soon)</option>
                                    <option value="Expired">Hết hạn (Expired)</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={() => { setIsAddModalOpen(false); setEditingDocId(null); }}
                                    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-blue-600 rounded-lg hover:bg-blue-700 shadow-sm shadow-blue-500/30"
                                >
                                    {editingDocId ? 'Cập nhật' : 'Lưu văn bản'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default ComplianceDocuments;
