import React, { useState, useEffect } from 'react';
import { 
  Download,
  Shield,
  Activity
} from 'lucide-react';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import complianceService, { ComplianceReport, GDPRSummary } from '../../features/security/services/complianceService';
import { formatDate } from '../../shared/utils/format';

const ComplianceReportingPage: React.FC = () => {
  const [report, setReport] = useState<ComplianceReport | null>(null);
  const [gdprSummary, setGdprSummary] = useState<GDPRSummary | null>(null);
  const [loading, setLoading] = useState(true);
  const [generating, setGenerating] = useState(false);
  const [dateRange, setDateRange] = useState({
    start_date: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    end_date: new Date().toISOString().split('T')[0],
  });

  useEffect(() => {
    fetchComplianceData();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dateRange]);

  const fetchComplianceData = async () => {
    try {
      setLoading(true);
      const [reportResponse, gdprResponse] = await Promise.all([
        complianceService.getComplianceReport(dateRange.start_date, dateRange.end_date),
        complianceService.getGDPRSummary(),
      ]);
      setReport(reportResponse.data);
      setGdprSummary(gdprResponse.data);
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to load compliance data');
    } finally {
      setLoading(false);
    }
  };

  const handleExport = async () => {
    try {
      setGenerating(true);
      const response = await complianceService.getComplianceReport(
        dateRange.start_date,
        dateRange.end_date,
        'csv'
      );
      
      // Create blob and download
      const blob = new Blob([response], { type: 'text/csv' });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `compliance_report_${dateRange.start_date}_to_${dateRange.end_date}.csv`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      
      toast.success('Compliance report exported successfully');
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to export compliance report');
    } finally {
      setGenerating(false);
    }
  };

  const getComplianceStatusColor = (status: string) => {
    switch (status) {
      case 'compliant':
        return 'bg-green-100 text-green-800 border-green-200';
      case 'pending_review':
        return 'bg-yellow-100 text-yellow-800 border-yellow-200';
      default:
        return 'bg-gray-100 text-gray-800 border-gray-200';
    }
  };

  if (loading) {
    return <Loading />;
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-8 flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 mb-2">Compliance Reporting</h1>
          <p className="text-gray-600">View compliance status and generate reports</p>
        </div>
        <button
          onClick={handleExport}
          disabled={generating}
          className="flex items-center space-x-2 px-4 py-2 bg-[var(--luxury-gold)] text-white rounded-lg hover:bg-[var(--luxury-gold-dark)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          <Download className="w-5 h-5" />
          <span>{generating ? 'Generating...' : 'Export CSV'}</span>
        </button>
      </div>

      {/* Date Range Filter */}
      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Start Date</label>
            <input
              type="date"
              value={dateRange.start_date}
              onChange={(e) => setDateRange({ ...dateRange, start_date: e.target.value })}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--luxury-gold)] focus:border-transparent"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">End Date</label>
            <input
              type="date"
              value={dateRange.end_date}
              onChange={(e) => setDateRange({ ...dateRange, end_date: e.target.value })}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--luxury-gold)] focus:border-transparent"
            />
          </div>
          <div className="flex items-end">
            <button
              onClick={fetchComplianceData}
              className="w-full px-4 py-2 bg-[var(--luxury-gold)] text-white rounded-lg hover:bg-[var(--luxury-gold-dark)] transition-colors"
            >
              Refresh Report
            </button>
          </div>
        </div>
      </div>

      {/* Compliance Status Overview */}
      {report && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
          <div className="bg-white rounded-lg shadow-md p-6">
            <div className="flex items-center justify-between mb-4">
              <div className="p-3 bg-blue-100 rounded-lg">
                <Activity className="w-6 h-6 text-blue-600" />
              </div>
              <span className={`px-3 py-1 rounded-full text-xs font-medium border ${getComplianceStatusColor(report.compliance_status)}`}>
                {report.compliance_status.replace('_', ' ')}
              </span>
            </div>
            <h3 className="text-sm font-medium text-gray-500 mb-1">Compliance Status</h3>
            <p className="text-2xl font-bold text-gray-900 capitalize">{report.compliance_status.replace('_', ' ')}</p>
          </div>

          <div className="bg-white rounded-lg shadow-md p-6">
            <div className="flex items-center justify-between mb-4">
              <div className="p-3 bg-green-100 rounded-lg">
                <DollarSign className="w-6 h-6 text-green-600" />
              </div>
            </div>
            <h3 className="text-sm font-medium text-gray-500 mb-1">Financial Actions</h3>
            <p className="text-2xl font-bold text-gray-900">{report.financial_audit.total_actions}</p>
            <p className="text-xs text-gray-500 mt-1">{report.financial_audit.description}</p>
          </div>

          <div className="bg-white rounded-lg shadow-md p-6">
            <div className="flex items-center justify-between mb-4">
              <div className="p-3 bg-purple-100 rounded-lg">
                <Shield className="w-6 h-6 text-purple-600" />
              </div>
            </div>
            <h3 className="text-sm font-medium text-gray-500 mb-1">GDPR Requests</h3>
            <p className="text-2xl font-bold text-gray-900">{report.gdpr_compliance.total_requests}</p>
            <p className="text-xs text-gray-500 mt-1">
              {report.gdpr_compliance.completed_requests} completed ({report.gdpr_compliance.completion_rate}%)
            </p>
          </div>

          <div className="bg-white rounded-lg shadow-md p-6">
            <div className="flex items-center justify-between mb-4">
              <div className="p-3 bg-orange-100 rounded-lg">
                <Activity className="w-6 h-6 text-orange-600" />
              </div>
            </div>
            <h3 className="text-sm font-medium text-gray-500 mb-1">Security Events</h3>
            <p className="text-2xl font-bold text-gray-900">{report.security_audit.total_events}</p>
            <p className="text-xs text-gray-500 mt-1">{report.security_audit.description}</p>
          </div>
        </div>
      )}

      {/* Detailed Reports */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Financial Audit Summary */}
        {report && (
          <div className="bg-white rounded-lg shadow-md p-6">
            <h2 className="text-xl font-bold text-gray-900 mb-4">Financial Audit Summary</h2>
            <div className="space-y-3">
              <div className="flex justify-between items-center">
                <span className="text-gray-600">Total Actions Logged</span>
                <span className="font-semibold text-gray-900">{report.financial_audit.total_actions}</span>
              </div>
              <div className="pt-3 border-t">
                <p className="text-sm text-gray-500">{report.financial_audit.description}</p>
              </div>
            </div>
          </div>
        )}

        {/* GDPR Compliance Summary */}
        {gdprSummary && (
          <div className="bg-white rounded-lg shadow-md p-6">
            <h2 className="text-xl font-bold text-gray-900 mb-4">GDPR Compliance Summary</h2>
            <div className="space-y-3">
              <div className="flex justify-between items-center">
                <span className="text-gray-600">Total Requests</span>
                <span className="font-semibold text-gray-900">{gdprSummary.total_requests}</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-gray-600">Pending Requests</span>
                <span className="font-semibold text-yellow-600">{gdprSummary.pending_requests}</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-gray-600">Completed Requests</span>
                <span className="font-semibold text-green-600">{gdprSummary.completed_requests}</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-gray-600">Completion Rate</span>
                <span className="font-semibold text-gray-900">{gdprSummary.completion_rate}%</span>
              </div>
              <div className="pt-3 border-t">
                <span className={`px-3 py-1 rounded-full text-xs font-medium border ${getComplianceStatusColor(gdprSummary.compliance_status)}`}>
                  {gdprSummary.compliance_status.replace('_', ' ')}
                </span>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* GDPR Requests by Type */}
      {gdprSummary && gdprSummary.requests_by_type && (
        <div className="bg-white rounded-lg shadow-md p-6 mt-6">
          <h2 className="text-xl font-bold text-gray-900 mb-4">GDPR Requests by Type</h2>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {Object.entries(gdprSummary.requests_by_type).map(([type, count]) => (
              <div key={type} className="bg-gray-50 p-4 rounded-lg">
                <p className="text-sm text-gray-500 capitalize mb-1">{type.replace('_', ' ')}</p>
                <p className="text-2xl font-bold text-gray-900">{count}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Report Period Info */}
      {report && (
        <div className="bg-white rounded-lg shadow-md p-6 mt-6">
          <div className="flex justify-between items-center">
            <div>
              <h3 className="text-lg font-semibold text-gray-900 mb-2">Report Period</h3>
              <p className="text-gray-600">
                {formatDate(report.period.start_date)} to {formatDate(report.period.end_date)}
              </p>
            </div>
            <div className="text-right">
              <p className="text-sm text-gray-500">Generated</p>
              <p className="text-sm text-gray-900">{formatDate(report.generated_at)}</p>
              <p className="text-xs text-gray-500 mt-1">by {report.generated_by}</p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ComplianceReportingPage;

