import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom';
import { FileSignature, CheckCircle, XCircle, Loader, Printer, Download } from 'lucide-react';
import { usePublicContract, useSignContract } from '../hooks/useContracts';
import { useQueryClient } from '@tanstack/react-query';

const ContractSigning: React.FC = () => {
  const { t } = useTranslation();
  const { token } = useParams<{ token: string }>();
  const queryClient = useQueryClient();
  const [signerName, setSignerName] = useState('');
  const [agreedToTerms, setAgreedToTerms] = useState(false);
  const [electronicConsent, setElectronicConsent] = useState(false);

  const { data: contractData, isLoading, error, refetch } = usePublicContract(token || '');
  const signMutation = useSignContract();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!token || !signerName.trim() || !agreedToTerms || !electronicConsent) return;

    try {
      await signMutation.mutateAsync({
        token,
        signer_name: signerName.trim(),
        consent_checkbox_checked: agreedToTerms,
        electronic_consent_given: electronicConsent,
      });
      // Refetch to get updated contract with signature data
      await refetch();
    } catch (error) {
      console.error('Failed to sign contract:', error);
    }
  };

  const handlePrint = () => {
    window.print();
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <Loader className="w-12 h-12 animate-spin text-blue-600 mx-auto mb-4" />
          <p className="text-gray-600">{t('common.loading')}</p>
        </div>
      </div>
    );
  }

  if (error || !contractData || !contractData.contract) {
    console.error('Contract loading error:', { error, contractData });
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="bg-white p-8 rounded-lg shadow-lg max-w-md text-center">
          <XCircle className="w-16 h-16 text-red-500 mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-gray-900 mb-2">
            {t('contracts.signing.notFound')}
          </h2>
          <p className="text-gray-600">
            This contract link is invalid or has expired.
          </p>
        </div>
      </div>
    );
  }

  if (contractData.is_expired) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="bg-white p-8 rounded-lg shadow-lg max-w-md text-center">
          <XCircle className="w-16 h-16 text-red-500 mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-gray-900 mb-2">
            {t('contracts.signing.expired')}
          </h2>
          <p className="text-gray-600">
            This contract has expired and can no longer be signed.
          </p>
        </div>
      </div>
    );
  }

  // Show signed contract view
  if (contractData.contract?.status === 'SIGNED' || signMutation.isSuccess) {
    return (
      <div className="min-h-screen bg-gray-50 py-8 print:py-0 print:bg-white">
        <div className="max-w-4xl mx-auto px-4 print:px-0 print:max-w-none">
          {/* Print Header - Only visible when printing */}
          <div className="hidden print:block mb-8 border-b-2 border-gray-300 pb-4">
            <div className="flex justify-between items-start">
              <div>
                <h1 className="text-2xl font-bold">{contractData.business.name}</h1>
                <p className="text-gray-600">{contractData.template.name}</p>
              </div>
              <div className="text-right text-sm text-gray-600">
                <p>Contract ID: {contractData.contract.id}</p>
                <p>Status: SIGNED</p>
              </div>
            </div>
          </div>

          {/* Success Banner - Hidden when printing */}
          <div className="bg-green-50 border border-green-200 rounded-lg p-6 mb-6 print:hidden">
            <div className="flex items-center gap-4">
              <CheckCircle className="w-12 h-12 text-green-500 flex-shrink-0" />
              <div>
                <h2 className="text-xl font-bold text-green-800">
                  Contract Successfully Signed
                </h2>
                <p className="text-green-700">
                  This contract has been signed and is now legally binding.
                </p>
              </div>
            </div>
          </div>

          {/* Action Buttons - Hidden when printing */}
          <div className="flex gap-4 mb-6 print:hidden">
            <button
              onClick={handlePrint}
              className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
            >
              <Printer className="w-5 h-5" />
              Print Contract
            </button>
          </div>

          {/* Contract Header */}
          <div className="bg-white rounded-lg shadow-lg p-8 mb-6 print:shadow-none print:p-0 print:mb-4">
            <div className="flex items-center gap-3 mb-4 print:hidden">
              {contractData.business.logo_url ? (
                <img
                  src={contractData.business.logo_url}
                  alt={contractData.business.name}
                  className="h-12 object-contain"
                />
              ) : (
                <FileSignature className="w-12 h-12 text-blue-600" />
              )}
              <div>
                <h1 className="text-2xl font-bold text-gray-900">
                  {contractData.business.name}
                </h1>
                <p className="text-gray-600">{contractData.template.name}</p>
              </div>
            </div>
            {contractData.customer && (
              <p className="text-gray-600">
                Contract for: <strong>{contractData.customer.name}</strong>
                {contractData.customer.email && ` (${contractData.customer.email})`}
              </p>
            )}
          </div>

          {/* Contract Content */}
          <div className="bg-white rounded-lg shadow-lg p-8 mb-6 print:shadow-none print:p-0 print:mb-4">
            <div
              className="prose max-w-none print:prose-sm"
              dangerouslySetInnerHTML={{ __html: contractData.contract.content }}
            />
          </div>

          {/* Signature Details */}
          <div className="bg-white rounded-lg shadow-lg p-8 print:shadow-none print:p-0 print:border-t-2 print:border-gray-300 print:pt-4">
            <h3 className="text-lg font-bold text-gray-900 mb-4 print:text-base">
              Electronic Signature Record
            </h3>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 print:gap-4">
              <div className="space-y-4">
                <div>
                  <p className="text-sm text-gray-500">Signer Name</p>
                  <p className="text-lg font-medium text-gray-900">
                    {contractData.signature?.signer_name || signerName || 'N/A'}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Signer Email</p>
                  <p className="text-gray-900">
                    {contractData.signature?.signer_email || contractData.customer?.email || 'N/A'}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Date Signed</p>
                  <p className="text-gray-900">
                    {contractData.signature?.signed_at
                      ? new Date(contractData.signature.signed_at).toLocaleString()
                      : new Date().toLocaleString()
                    }
                  </p>
                </div>
              </div>

              <div className="space-y-4">
                <div>
                  <p className="text-sm text-gray-500">Electronic Signature</p>
                  <div className="mt-2 p-4 bg-gray-50 border border-gray-200 rounded-lg print:bg-white print:border-gray-400">
                    <p className="text-2xl italic text-gray-800" style={{ fontFamily: 'cursive' }}>
                      {contractData.signature?.signer_name || signerName || 'N/A'}
                    </p>
                  </div>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Contract Status</p>
                  <span className="inline-flex items-center gap-1 px-3 py-1 bg-green-100 text-green-800 rounded-full text-sm font-medium print:bg-transparent print:text-green-700 print:px-0">
                    <CheckCircle className="w-4 h-4" />
                    Signed
                  </span>
                </div>
              </div>
            </div>

            {/* Legal Notice */}
            <div className="mt-6 pt-6 border-t border-gray-200 print:mt-4 print:pt-4">
              <p className="text-xs text-gray-500 print:text-gray-600">
                This document was signed electronically in compliance with the Electronic Signatures in Global and National Commerce Act (ESIGN Act, 15 U.S.C. section 7001 et seq.) and the Uniform Electronic Transactions Act (UETA). The signer expressly agreed to the terms and conditions, consented to conduct business electronically, and acknowledged that their electronic signature is the legal equivalent of a handwritten signature. A complete audit trail including timestamp, IP address, and document hash is maintained.
              </p>
            </div>
          </div>

          {/* Print Footer - Only visible when printing */}
          <div className="hidden print:block mt-8 pt-4 border-t border-gray-300 text-xs text-gray-500">
            <p>Printed on: {new Date().toLocaleString()}</p>
            <p>This is a copy of an electronically signed document.</p>
          </div>
        </div>
      </div>
    );
  }

  // Show signing form
  return (
    <div className="min-h-screen bg-gray-50 py-12">
      <div className="max-w-4xl mx-auto px-4">
        {/* Header */}
        <div className="bg-white rounded-lg shadow-lg p-8 mb-6">
          <div className="flex items-center gap-3 mb-4">
            {contractData.business.logo_url ? (
              <img
                src={contractData.business.logo_url}
                alt={contractData.business.name}
                className="h-12 object-contain"
              />
            ) : (
              <FileSignature className="w-12 h-12 text-blue-600" />
            )}
            <div>
              <h1 className="text-2xl font-bold text-gray-900">
                {contractData.business.name}
              </h1>
              <p className="text-gray-600">{contractData.template.name}</p>
            </div>
          </div>
          {contractData.customer && (
            <p className="text-gray-600">
              {t('contracts.signing.contractFor', {
                customerName: contractData.customer.name,
              })}
            </p>
          )}
        </div>

        {/* Contract Content */}
        <div className="bg-white rounded-lg shadow-lg p-8 mb-6 overflow-auto">
          <div
            className="prose max-w-none"
            dangerouslySetInnerHTML={{ __html: contractData.contract.content }}
          />
        </div>

        {/* Signature Form */}
        {contractData.can_sign && (
          <div className="bg-white rounded-lg shadow-lg p-8">
            <h2 className="text-xl font-bold text-gray-900 mb-4">
              {t('contracts.signing.title')}
            </h2>
            <p className="text-gray-600 mb-6">
              {t('contracts.signing.pleaseReview')}
            </p>

            <form onSubmit={handleSubmit}>
              <div className="space-y-6">
                {/* Electronic Signature - Type Name */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Type your full legal name to sign
                  </label>
                  <div className="relative">
                    <input
                      type="text"
                      value={signerName}
                      onChange={(e) => setSignerName(e.target.value)}
                      placeholder="Enter your full name"
                      className="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-lg"
                      required
                    />
                  </div>
                  {signerName && (
                    <div className="mt-4 p-4 bg-gray-50 border border-gray-200 rounded-lg">
                      <p className="text-xs text-gray-500 mb-2">Signature Preview:</p>
                      <p className="text-2xl italic text-gray-800" style={{ fontFamily: 'cursive' }}>
                        {signerName}
                      </p>
                    </div>
                  )}
                </div>

                {/* Consent Checkboxes - Text must match backend storage for legal compliance */}
                <div className="space-y-4 p-4 bg-gray-50 rounded-lg border border-gray-200">
                  <div className="flex items-start gap-3">
                    <input
                      type="checkbox"
                      id="agree"
                      checked={agreedToTerms}
                      onChange={(e) => setAgreedToTerms(e.target.checked)}
                      className="w-5 h-5 mt-0.5 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                      required
                    />
                    <label htmlFor="agree" className="text-sm text-gray-700">
                      I have read and agree to the terms and conditions outlined in this document. By checking this box, I understand that this constitutes a legal electronic signature under the ESIGN Act (15 U.S.C. section 7001 et seq.) and UETA.
                    </label>
                  </div>

                  <div className="flex items-start gap-3">
                    <input
                      type="checkbox"
                      id="electronic-consent"
                      checked={electronicConsent}
                      onChange={(e) => setElectronicConsent(e.target.checked)}
                      className="w-5 h-5 mt-0.5 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                      required
                    />
                    <label htmlFor="electronic-consent" className="text-sm text-gray-700">
                      <span className="font-medium">I consent to conduct business electronically.</span> I understand that: (1) I am agreeing to use electronic records and signatures in place of paper; (2) I have the right to receive documents in paper form upon request; (3) I can withdraw this consent at any time; (4) I need internet access to access these documents; (5) I can request a paper copy at any time.
                    </label>
                  </div>
                </div>

                <button
                  type="submit"
                  disabled={signMutation.isPending || !agreedToTerms || !electronicConsent || !signerName.trim()}
                  className="w-full px-6 py-4 bg-blue-600 text-white text-lg font-semibold rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                >
                  {signMutation.isPending ? (
                    <>
                      <Loader className="w-5 h-5 animate-spin" />
                      Signing...
                    </>
                  ) : (
                    <>
                      <FileSignature className="w-5 h-5" />
                      Sign Contract
                    </>
                  )}
                </button>

                {signMutation.isError && (
                  <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
                    <p className="text-sm text-red-600">
                      Failed to sign the contract. Please try again.
                    </p>
                  </div>
                )}
              </div>
            </form>
          </div>
        )}
      </div>
    </div>
  );
};

export default ContractSigning;
