import React, { useState, useCallback } from 'react';
import { CheckCircleIcon, XCircleIcon, EyeSlashIcon, ArrowDownTrayIcon, FunnelIcon } from '@heroicons/react/24/outline';
import { apiClient } from '../../../utils/api';
import { toast } from 'react-toastify';

const IssueManagement = ({ issues = [], onIssuesUpdate, auditId }) => {
    const [selectedIssues, setSelectedIssues] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [filterSeverity, setFilterSeverity] = useState('all');
    const [filterType, setFilterType] = useState('all');
    const [showIgnored, setShowIgnored] = useState(false);
    const [sortBy, setSortBy] = useState('priority');

    // Handle issue selection
    const handleSelectIssue = (issueId) => {
        setSelectedIssues(prev => 
            prev.includes(issueId) 
                ? prev.filter(id => id !== issueId)
                : [...prev, issueId]
        );
    };

    // Select all issues
    const handleSelectAll = () => {
        if (selectedIssues.length === getFilteredIssues().length) {
            setSelectedIssues([]);
        } else {
            setSelectedIssues(getFilteredIssues().map(issue => issue.id));
        }
    };

    // Ignore selected issues
    const handleIgnoreIssues = async (reason = '') => {
        if (selectedIssues.length === 0) {
            toast.warning('Please select issues to ignore');
            return;
        }

        setIsLoading(true);
        try {
            const response = await apiClient.post('/audit/issues/ignore', {
                issue_ids: selectedIssues,
                ignore_reason: reason,
                audit_id: auditId
            });

            if (response.data.success) {
                toast.success(`${response.data.ignored_count} issues marked as ignored`);
                setSelectedIssues([]);
                if (onIssuesUpdate) {
                    onIssuesUpdate();
                }
            }
        } catch (error) {
            toast.error('Failed to ignore issues: ' + error.message);
        } finally {
            setIsLoading(false);
        }
    };

    // Restore ignored issues
    const handleRestoreIssues = async () => {
        if (selectedIssues.length === 0) {
            toast.warning('Please select issues to restore');
            return;
        }

        setIsLoading(true);
        try {
            const response = await apiClient.post('/audit/issues/restore', {
                issue_ids: selectedIssues,
                audit_id: auditId
            });

            if (response.data.success) {
                toast.success(`${response.data.restored_count} issues restored`);
                setSelectedIssues([]);
                if (onIssuesUpdate) {
                    onIssuesUpdate();
                }
            }
        } catch (error) {
            toast.error('Failed to restore issues: ' + error.message);
        } finally {
            setIsLoading(false);
        }
    };

    // Export audit report
    const handleExport = async (format = 'csv') => {
        setIsLoading(true);
        try {
            const response = await apiClient.get('/audit/export', {
                params: { format, audit_id: auditId },
                responseType: format === 'csv' ? 'blob' : 'json'
            });

            if (format === 'csv') {
                // Download CSV file
                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', `audit-report-${new Date().toISOString().split('T')[0]}.csv`);
                document.body.appendChild(link);
                link.click();
                link.remove();
                toast.success('CSV report downloaded');
            } else if (format === 'pdf') {
                // Open PDF URL in new tab
                if (response.data.pdf_url) {
                    window.open(response.data.pdf_url, '_blank');
                    toast.success('PDF report is being generated');
                }
            }
        } catch (error) {
            toast.error('Failed to export report: ' + error.message);
        } finally {
            setIsLoading(false);
        }
    };

    // Filter and sort issues
    const getFilteredIssues = useCallback(() => {
        let filtered = [...issues];

        // Filter by ignored status
        if (!showIgnored) {
            filtered = filtered.filter(issue => !issue.is_ignored);
        }

        // Filter by severity
        if (filterSeverity !== 'all') {
            filtered = filtered.filter(issue => issue.severity === filterSeverity);
        }

        // Filter by type
        if (filterType !== 'all') {
            filtered = filtered.filter(issue => issue.type === filterType);
        }

        // Sort issues
        filtered.sort((a, b) => {
            switch (sortBy) {
                case 'priority':
                    return (b.priority_score || 0) - (a.priority_score || 0);
                case 'severity':
                    const severityOrder = { critical: 5, high: 4, medium: 3, low: 2, warning: 1, notice: 0 };
                    return severityOrder[b.severity] - severityOrder[a.severity];
                case 'type':
                    return a.type.localeCompare(b.type);
                default:
                    return 0;
            }
        });

        return filtered;
    }, [issues, showIgnored, filterSeverity, filterType, sortBy]);

    // Get unique issue types for filter
    const issueTypes = [...new Set(issues.map(issue => issue.type))];

    // Get severity badge color
    const getSeverityColor = (severity) => {
        const colors = {
            critical: 'pr:bg-red-100 pr:text-red-800',
            high: 'pr:bg-orange-100 pr:text-orange-800',
            medium: 'pr:bg-yellow-100 pr:text-yellow-800',
            low: 'pr:bg-blue-100 pr:text-blue-800',
            warning: 'pr:bg-gray-100 pr:text-gray-800',
            notice: 'pr:bg-green-100 pr:text-green-800'
        };
        return colors[severity] || 'pr:bg-gray-100 pr:text-gray-800';
    };

    const filteredIssues = getFilteredIssues();

    return (
        <div className="issue-management">
            {/* Toolbar */}
            <div className="pr:bg-white pr:shadow-xs pr:rounded-lg pr:p-4 pr:mb-4">
                <div className="pr:flex pr:flex-wrap pr:items-center pr:justify-between pr:gap-4">
                    {/* Filters */}
                    <div className="pr:flex pr:items-center pr:gap-3">
                        <FunnelIcon className="pr:h-5 pr:w-5 pr:text-gray-400" />
                        
                        <select
                            value={filterSeverity}
                            onChange={(e) => setFilterSeverity(e.target.value)}
                            className="pr:rounded-md pr:border-gray-300 pr:text-sm"
                        >
                            <option value="all">All Severities</option>
                            <option value="critical">Critical</option>
                            <option value="high">High</option>
                            <option value="medium">Medium</option>
                            <option value="low">Low</option>
                            <option value="warning">Warning</option>
                        </select>

                        <select
                            value={filterType}
                            onChange={(e) => setFilterType(e.target.value)}
                            className="pr:rounded-md pr:border-gray-300 pr:text-sm"
                        >
                            <option value="all">All Types</option>
                            {issueTypes.map(type => (
                                <option key={type} value={type}>
                                    {type.replace(/_/g, ' ').charAt(0).toUpperCase() + type.slice(1)}
                                </option>
                            ))}
                        </select>

                        <select
                            value={sortBy}
                            onChange={(e) => setSortBy(e.target.value)}
                            className="pr:rounded-md pr:border-gray-300 pr:text-sm"
                        >
                            <option value="priority">Sort by Priority</option>
                            <option value="severity">Sort by Severity</option>
                            <option value="type">Sort by Type</option>
                        </select>

                        <label className="pr:flex pr:items-center pr:gap-2 pr:text-sm">
                            <input
                                type="checkbox"
                                checked={showIgnored}
                                onChange={(value) => setShowIgnored(value?.target ? value.target.checked : !!value)}
                                className="pr:rounded pr:border-gray-300"
                            />
                            Show Ignored
                        </label>
                    </div>

                    {/* Actions */}
                    <div className="pr:flex pr:items-center pr:gap-2">
                        {selectedIssues.length > 0 && (
                            <>
                                <span className="pr:text-sm pr:text-gray-500">
                                    {selectedIssues.length} selected
                                </span>
                                
                                {!showIgnored && (
                                    <button
                                        onClick={() => handleIgnoreIssues()}
                                        disabled={isLoading}
                                        className="pr:inline-flex pr:items-center pr:px-3 pr:py-1.5 pr:border pr:border-gray-300 pr:text-sm pr:font-medium pr:rounded-md pr:text-gray-700 pr:bg-white pr:hover:bg-gray-50"
                                    >
                                        <EyeSlashIcon className="pr:h-4 pr:w-4 pr:mr-1" />
                                        Ignore
                                    </button>
                                )}
                                
                                {showIgnored && (
                                    <button
                                        onClick={handleRestoreIssues}
                                        disabled={isLoading}
                                        className="pr:inline-flex pr:items-center pr:px-3 pr:py-1.5 pr:border pr:border-gray-300 pr:text-sm pr:font-medium pr:rounded-md pr:text-gray-700 pr:bg-white pr:hover:bg-gray-50"
                                    >
                                        <CheckCircleIcon className="pr:h-4 pr:w-4 pr:mr-1" />
                                        Restore
                                    </button>
                                )}
                            </>
                        )}

                        <div className="pr:relative pr:group">
                            <button
                                className="pr:inline-flex pr:items-center pr:px-3 pr:py-1.5 pr:border pr:border-gray-300 pr:text-sm pr:font-medium pr:rounded-md pr:text-gray-700 pr:bg-white pr:hover:bg-gray-50"
                            >
                                <ArrowDownTrayIcon className="pr:h-4 pr:w-4 pr:mr-1" />
                                Export
                            </button>
                            <div className="pr:absolute pr:right-0 pr:mt-2 pr:w-48 pr:rounded-md pr:shadow-lg pr:bg-white pr:ring-1 pr:ring-black pr:ring-opacity-5 pr:hidden pr:group-hover:block pr:z-10">
                                <div className="pr:py-1">
                                    <button
                                        onClick={() => handleExport('csv')}
                                        className="pr:block pr:w-full pr:text-left pr:px-4 pr:py-2 pr:text-sm pr:text-gray-700 pr:hover:bg-gray-100"
                                    >
                                        Export as CSV
                                    </button>
                                    <button
                                        onClick={() => handleExport('pdf')}
                                        className="pr:block pr:w-full pr:text-left pr:px-4 pr:py-2 pr:text-sm pr:text-gray-700 pr:hover:bg-gray-100"
                                    >
                                        Export as PDF
                                    </button>
                                    <button
                                        onClick={() => handleExport('json')}
                                        className="pr:block pr:w-full pr:text-left pr:px-4 pr:py-2 pr:text-sm pr:text-gray-700 pr:hover:bg-gray-100"
                                    >
                                        Export as JSON
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Issues List */}
            <div className="pr:bg-white pr:shadow-xs pr:rounded-lg pr:overflow-hidden">
                <table className="pr:min-w-full pr:divide-y pr:divide-gray-200">
                    <thead className="pr:bg-gray-50">
                        <tr>
                            <th className="pr:px-6 pr:py-3 pr:text-left">
                                <input
                                    type="checkbox"
                                    checked={selectedIssues.length === filteredIssues.length && filteredIssues.length > 0}
                                    onChange={handleSelectAll}
                                    className="pr:rounded pr:border-gray-300"
                                />
                            </th>
                            <th className="pr:px-6 pr:py-3 pr:text-left pr:text-xs pr:font-medium pr:text-gray-500 pr:uppercase pr:tracking-wider">
                                Severity
                            </th>
                            <th className="pr:px-6 pr:py-3 pr:text-left pr:text-xs pr:font-medium pr:text-gray-500 pr:uppercase pr:tracking-wider">
                                Issue
                            </th>
                            <th className="pr:px-6 pr:py-3 pr:text-left pr:text-xs pr:font-medium pr:text-gray-500 pr:uppercase pr:tracking-wider">
                                Type
                            </th>
                            <th className="pr:px-6 pr:py-3 pr:text-left pr:text-xs pr:font-medium pr:text-gray-500 pr:uppercase pr:tracking-wider">
                                Priority
                            </th>
                            <th className="pr:px-6 pr:py-3 pr:text-left pr:text-xs pr:font-medium pr:text-gray-500 pr:uppercase pr:tracking-wider">
                                Status
                            </th>
                            <th className="pr:px-6 pr:py-3 pr:text-left pr:text-xs pr:font-medium pr:text-gray-500 pr:uppercase pr:tracking-wider">
                                Actions
                            </th>
                        </tr>
                    </thead>
                    <tbody className="pr:bg-white pr:divide-y pr:divide-gray-200">
                        {filteredIssues.map((issue) => (
                            <tr key={issue.id} className={issue.is_ignored ? 'pr:opacity-60' : ''}>
                                <td className="pr:px-6 pr:py-4 pr:whitespace-nowrap">
                                    <input
                                        type="checkbox"
                                        checked={selectedIssues.includes(issue.id)}
                                        onChange={() => handleSelectIssue(issue.id)}
                                        className="pr:rounded pr:border-gray-300"
                                    />
                                </td>
                                <td className="pr:px-6 pr:py-4 pr:whitespace-nowrap">
                                    <span className={`pr:px-2 pr:py-1 pr:text-xs pr:font-medium pr:rounded-full ${getSeverityColor(issue.severity)}`}>
                                        {issue.severity}
                                    </span>
                                </td>
                                <td className="pr:px-6 pr:py-4">
                                    <div className="pr:text-sm pr:text-gray-900">{issue.title}</div>
                                    <div className="pr:text-sm pr:text-gray-500">{issue.description}</div>
                                    {issue.affected_url && (
                                        <div className="pr:text-xs pr:text-gray-400 pr:mt-1">
                                            URL: {issue.affected_url}
                                        </div>
                                    )}
                                </td>
                                <td className="pr:px-6 pr:py-4 pr:whitespace-nowrap pr:text-sm pr:text-gray-500">
                                    {issue.type.replace(/_/g, ' ')}
                                </td>
                                <td className="pr:px-6 pr:py-4 pr:whitespace-nowrap">
                                    <div className="pr:text-sm pr:text-gray-900">
                                        {issue.priority_score || 0}
                                    </div>
                                </td>
                                <td className="pr:px-6 pr:py-4 pr:whitespace-nowrap">
                                    {issue.is_ignored ? (
                                        <span className="pr:text-xs pr:text-gray-500">Ignored</span>
                                    ) : issue.is_fixed ? (
                                        <span className="pr:text-xs pr:text-green-600">Fixed</span>
                                    ) : (
                                        <span className="pr:text-xs pr:text-orange-600">Active</span>
                                    )}
                                </td>
                                <td className="pr:px-6 pr:py-4 pr:whitespace-nowrap pr:text-sm">
                                    {issue.fix_available && !issue.is_fixed && !issue.is_ignored && (
                                        <button
                                            className="pr:text-indigo-600 pr:hover:text-indigo-900"
                                            onClick={() => {/* Apply fix handler to be implemented */}}
                                        >
                                            Fix
                                        </button>
                                    )}
                                    {issue.how_to_fix && (
                                        <button
                                            className="pr:ml-2 pr:text-gray-600 pr:hover:text-gray-900"
                                            onClick={() => alert(issue.how_to_fix)}
                                        >
                                            Help
                                        </button>
                                    )}
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
                
                {filteredIssues.length === 0 && (
                    <div className="pr:text-center pr:py-8 pr:text-gray-500">
                        No issues found matching your filters
                    </div>
                )}
            </div>
        </div>
    );
};

export default IssueManagement;
