import React, { useEffect, useState, useRef } from 'react';
import { Download, Trash2, AlertCircle, Info } from 'lucide-react';
import gdprService, { GDPRRequest } from '../../features/compliance/services/gdprService';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import { formatDate } from '../../shared/utils/format';

const GDPRPage: React.FC = () => {
  const [requests, setRequests] = useState<GDPRRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [requesting, setRequesting] = useState(false);
  const abortControllerRef = useRef<AbortController | null>(null);

  useEffect(() => {
    // Cancel previous request if exists
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }

    // Create new abort controller
    abortControllerRef.current = new AbortController();

    fetchRequests();

    // Cleanup: abort request on unmount
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, []);

  const fetchRequests = async () => {
    try {
      setLoading(true);
      const response = await gdprService.getMyRequests();
      setRequests(response.data.requests || []);
    } catch (error: unknown) {
      const isAbortError = (e: unknown): boolean => {
        if (typeof e === 'object' && e !== null) {
          const err = e as { name?: string; code?: string };
          return err.name === 'AbortError' || err.code === 'ERR_CANCELED';
        }
        return false;
      };
      if (isAbortError(error)) {
        return;
      }
      toast.error(getUserFriendlyError(error) || 'Unable to load GDPR requests');
    } finally {
      setLoading(false);
    }
  };

  const handleRequestExport = async () => {
    if (!confirm('Request a copy of your personal data? You will receive an email when ready.')) return;

    try {
      setRequesting(true);
      await gdprService.requestDataExport();
      toast.success('Data export request created. You will receive an email when ready.');
      fetchRequests();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to create export request');
    } finally {
      setRequesting(false);
    }
  };

  const handleRequestDeletion = async () => {
    if (!confirm('WARNING: This will permanently delete your account and all associated data. This action cannot be undone. Are you absolutely sure?')) return;
    if (!confirm('This is your last chance. Are you 100% certain you want to delete all your data?')) return;

    try {
      setRequesting(true);
      await gdprService.requestDataDeletion();
      toast.success('Deletion request created. Please check your email to confirm.');
      fetchRequests();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to create deletion request');
    } finally {
      setRequesting(false);
    }
  };

  const handleDownload = async (request: GDPRRequest) => {
    if (!request.verification_token) {
      toast.error('Verification token not available');
      return;
    }

    try {
      // SECURITY/COMPLIANCE: Secure download of GDPR data export
      // Export is downloaded as blob (binary data) for security
      // Filename indicates JSON format (machine-readable as required by GDPR Article 20)
      const blob = await gdprService.downloadExport(request.id, request.verification_token);
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      // GDPR Article 20: Data must be in machine-readable format (JSON)
      a.download = `user_data_export_${request.id}.json`;
      document.body.appendChild(a);
      a.click();
      // SECURITY: Revoke object URL immediately after use
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      toast.success('Export downloaded');
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to download export');
    }
  };

  if (loading) {
    return <Loading fullScreen text="Loading..." />;
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50 px-3 sm:px-4 md:px-6 lg:px-8 py-6 sm:py-8 md:py-10">
      <div className="max-w-4xl mx-auto">
        <div className="mb-6 sm:mb-8 md:mb-10 animate-fade-in">
          <div className="flex items-center gap-2 sm:gap-3 mb-2 sm:mb-3">
            <div className="h-1 w-12 sm:w-16 md:w-20 bg-gradient-to-r from-blue-400 via-indigo-500 to-purple-600 rounded-full"></div>
            <h1 className="text-2xl sm:text-3xl md:text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
              Data Privacy (GDPR)
            </h1>
          </div>
          <p className="text-slate-600 mt-2 sm:mt-3 text-sm sm:text-base md:text-lg font-light">
            Manage your personal data and privacy rights
          </p>
        </div>

        <div className="space-y-4 sm:space-y-5 md:space-y-6">
          {/* Data Export */}
          <div className="bg-white/90 backdrop-blur-md rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 lg:p-8 animate-fade-in hover:shadow-2xl transition-all duration-300">
            <div className="flex flex-col sm:flex-row items-start gap-3 sm:gap-4 mb-3 sm:mb-4">
              <Download className="w-6 h-6 sm:w-7 sm:h-7 text-blue-500 flex-shrink-0 mt-1" />
              <div className="flex-1 min-w-0">
                <h2 className="text-lg sm:text-xl md:text-2xl font-semibold mb-2 text-slate-900">Export Your Data</h2>
                <p className="text-xs sm:text-sm md:text-base text-slate-600 mb-3 sm:mb-4">
                  Request a copy of all your personal data stored in our system. You will receive an email with a download link when your data is ready.
                </p>
                <button
                  onClick={handleRequestExport}
                  disabled={requesting}
                  className="w-full sm:w-auto px-4 sm:px-6 py-2 sm:py-2.5 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-xl font-semibold hover:from-blue-700 hover:to-blue-800 shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 text-xs sm:text-sm"
                >
                  {requesting ? 'Requesting...' : 'Request Data Export'}
                </button>
              </div>
            </div>
          </div>

          {/* Data Deletion */}
          <div className="bg-white/90 backdrop-blur-md rounded-xl sm:rounded-2xl shadow-xl border-2 border-red-200/60 p-4 sm:p-5 md:p-6 lg:p-8 animate-fade-in hover:shadow-2xl transition-all duration-300" style={{ animationDelay: '0.1s' }}>
            <div className="flex flex-col sm:flex-row items-start gap-3 sm:gap-4 mb-3 sm:mb-4">
              <Trash2 className="w-6 h-6 sm:w-7 sm:h-7 text-red-500 flex-shrink-0 mt-1" />
              <div className="flex-1 min-w-0">
                <h2 className="text-lg sm:text-xl md:text-2xl font-semibold mb-2 text-red-900">Delete Your Data</h2>
                <div className="bg-gradient-to-r from-red-50 to-rose-50 border-2 border-red-200 rounded-lg sm:rounded-xl p-3 sm:p-4 mb-3 sm:mb-4">
                  <div className="flex items-start gap-2 sm:gap-3">
                    <AlertCircle className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" />
                    <div>
                      <p className="text-xs sm:text-sm text-red-800 font-semibold mb-1">Warning: This action cannot be undone</p>
                      <p className="text-xs sm:text-sm text-red-700 mb-2">
                        Requesting data deletion will permanently remove your account and all associated data including bookings, payments, and personal information. This action is irreversible.
                      </p>
                      <p className="text-xs sm:text-sm text-red-700 font-medium">
                        📧 <strong>Email Confirmation Required:</strong> After submitting your deletion request, you will receive an email with a confirmation link. You must click the link in the email to confirm the deletion. The link will expire after 24 hours for security reasons.
                      </p>
                    </div>
                  </div>
                </div>
                <button
                  onClick={handleRequestDeletion}
                  disabled={requesting}
                  className="w-full sm:w-auto px-4 sm:px-6 py-2 sm:py-2.5 bg-gradient-to-r from-red-600 to-red-700 text-white rounded-xl font-semibold hover:from-red-700 hover:to-red-800 shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 text-xs sm:text-sm"
                >
                  {requesting ? 'Requesting...' : 'Request Data Deletion'}
                </button>
              </div>
            </div>
          </div>

          {/* Data Retention Information */}
          <div className="bg-white/90 backdrop-blur-md rounded-xl sm:rounded-2xl shadow-xl border border-blue-200/60 p-4 sm:p-5 md:p-6 lg:p-8 animate-fade-in hover:shadow-2xl transition-all duration-300" style={{ animationDelay: '0.2s' }}>
            <div className="flex flex-col sm:flex-row items-start gap-3 sm:gap-4 mb-3 sm:mb-4">
              <Info className="w-6 h-6 sm:w-7 sm:h-7 text-blue-500 flex-shrink-0 mt-1" />
              <div className="flex-1 min-w-0">
                <h2 className="text-lg sm:text-xl md:text-2xl font-semibold mb-2 text-slate-900">Data Retention Policy</h2>
                <p className="text-xs sm:text-sm md:text-base text-slate-600 mb-3 sm:mb-4">
                  Understanding how long we retain your data and why:
                </p>
                <div className="space-y-2 sm:space-y-3">
                  <div className="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg sm:rounded-xl p-3 sm:p-4">
                    <p className="text-xs sm:text-sm font-semibold text-blue-900 mb-1">Personal Data</p>
                    <p className="text-xs sm:text-sm text-blue-800">
                      Deleted upon your request (GDPR Article 17 - Right to Erasure). You can request deletion at any time using the option above.
                    </p>
                  </div>
                  <div className="bg-gradient-to-r from-amber-50 to-yellow-50 border border-amber-200 rounded-lg sm:rounded-xl p-3 sm:p-4">
                    <p className="text-xs sm:text-sm font-semibold text-amber-900 mb-1">Financial Records</p>
                    <p className="text-xs sm:text-sm text-amber-800">
                      Retained for 7 years as required by law for accounting and tax purposes. This includes invoices, payment records, and transaction history.
                    </p>
                  </div>
                  <div className="bg-gradient-to-r from-slate-50 to-gray-50 border border-slate-200 rounded-lg sm:rounded-xl p-3 sm:p-4">
                    <p className="text-xs sm:text-sm font-semibold text-slate-900 mb-1">Booking Records</p>
                    <p className="text-xs sm:text-sm text-slate-700">
                      Retained for service history and customer support purposes. Personal identifiers can be anonymized upon request while maintaining service records.
                    </p>
                  </div>
                  <div className="bg-gradient-to-r from-purple-50 to-pink-50 border border-purple-200 rounded-lg sm:rounded-xl p-3 sm:p-4">
                    <p className="text-xs sm:text-sm font-semibold text-purple-900 mb-1">Security Logs</p>
                    <p className="text-xs sm:text-sm text-purple-800">
                      Retained for security and fraud prevention purposes. Logs are automatically purged after the retention period.
                    </p>
                  </div>
                </div>
                <p className="text-xs sm:text-sm text-slate-500 mt-3 sm:mt-4 italic">
                  Note: Some data may be retained longer if required by law, legal proceedings, or active disputes. 
                  For specific questions about data retention, please contact our support team.
                </p>
              </div>
            </div>
          </div>

          {/* Request History */}
          {requests.length > 0 && (
            <div className="bg-white/90 backdrop-blur-md rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 lg:p-8 animate-fade-in hover:shadow-2xl transition-all duration-300" style={{ animationDelay: '0.2s' }}>
              <h2 className="text-lg sm:text-xl md:text-2xl font-semibold mb-3 sm:mb-4 md:mb-5 text-slate-900">Request History</h2>
              <div className="space-y-3 sm:space-y-4">
                {requests.map((request) => (
                  <div
                    key={request.id}
                    className="bg-gradient-to-r from-slate-50 to-white border border-slate-200 rounded-lg sm:rounded-xl p-3 sm:p-4 hover:from-blue-50 hover:to-indigo-50 hover:border-blue-300 hover:shadow-md transition-all duration-200"
                  >
                    <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4">
                      <div className="flex-1 min-w-0">
                        <div className="flex flex-wrap items-center gap-2 sm:gap-3 mb-2">
                          {request.request_type === 'data_export' ? (
                            <Download className="w-5 h-5 text-blue-500 flex-shrink-0" />
                          ) : (
                            <Trash2 className="w-5 h-5 text-red-500 flex-shrink-0" />
                          )}
                          <h3 className="font-semibold text-sm sm:text-base">
                            {request.request_type === 'data_export' ? 'Data Export' : 'Data Deletion'}
                          </h3>
                          <span className={`px-2 sm:px-3 py-1 rounded-full text-xs font-semibold border shadow-sm ${
                            request.status === 'completed' ? 'bg-gradient-to-r from-emerald-50 to-green-50 text-emerald-800 border-emerald-200' :
                            request.status === 'pending' ? 'bg-gradient-to-r from-amber-50 to-yellow-50 text-amber-800 border-amber-200' :
                            'bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-200'
                          }`}>
                            {request.status}
                          </span>
                        </div>
                        <p className="text-xs sm:text-sm text-slate-600">
                          Created: {formatDate(request.created_at)}
                          {request.processed_at && ` • Processed: ${formatDate(request.processed_at)}`}
                        </p>
                      </div>
                      {request.request_type === 'data_export' && request.status === 'completed' && (
                        <button
                          onClick={() => handleDownload(request)}
                          className="w-full sm:w-auto px-3 sm:px-4 py-2 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-lg sm:rounded-xl hover:from-blue-700 hover:to-blue-800 shadow-lg hover:shadow-xl transition-all duration-200 text-xs sm:text-sm font-semibold"
                        >
                          Download
                        </button>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default GDPRPage;

