/**
 * KYCVerification Page
 * Standalone page for KYC verification process
 * Epic: OQI-004 Cuentas de Inversion
 */

import React, { useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { ArrowLeft, AlertCircle } from 'lucide-react';
import { KYCVerificationPanel } from '../components/KYCVerificationPanel';
import { KYCStatus } from '../components/KYCStatusBadge';

interface KYCData {
  status: KYCStatus;
  personalData?: {
    fullName: string;
    dateOfBirth: string;
    nationality: string;
    address: string;
    city: string;
    state: string;
    postalCode: string;
    country: string;
    occupation: string;
    incomeSource: string;
  };
  documents?: Array<{
    id: string;
    type: 'id_front' | 'id_back' | 'proof_of_address' | 'selfie';
    fileName: string;
    status: 'pending' | 'approved' | 'rejected';
    rejectionReason?: string;
  }>;
  rejectionReason?: string;
}

export const KYCVerification: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [kycData, setKycData] = useState<KYCData>({
    status: 'not_started',
  });

  useEffect(() => {
    loadKYCStatus();
  }, []);

  const loadKYCStatus = async () => {
    try {
      setLoading(true);
      setError(null);

      const token = localStorage.getItem('token');
      if (!token) {
        navigate('/login');
        return;
      }

      const response = await fetch('/api/v1/investment/kyc/status', {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (response.ok) {
        const data = await response.json();
        setKycData(data.data || { status: 'not_started' });
      } else if (response.status === 404) {
        setKycData({ status: 'not_started' });
      } else {
        throw new Error('Error loading KYC status');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error loading KYC status');
      setKycData({ status: 'not_started' });
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (data: { personalData: { fullName: string; dateOfBirth: string; nationality: string; address: string; city: string; state: string; postalCode: string; country: string; occupation: string; incomeSource: string }; documents: File[] }) => {
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('Please log in to continue');
    }

    const formData = new FormData();
    formData.append('personalData', JSON.stringify(data.personalData));
    data.documents.forEach((file, index) => {
      formData.append(`document_${index}`, file);
    });

    const response = await fetch('/api/v1/investment/kyc/submit', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${token}`,
      },
      body: formData,
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || 'Failed to submit KYC');
    }

    setKycData(prev => ({ ...prev, status: 'pending' }));
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-96">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto px-4 py-8">
      <div className="flex items-center gap-4 mb-8">
        <Link
          to="/investment/portfolio"
          className="p-2 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700"
        >
          <ArrowLeft className="w-5 h-5 text-gray-600 dark:text-gray-400" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
            Verificación de Identidad
          </h1>
          <p className="text-gray-500 dark:text-gray-400">
            Completa tu verificación KYC para habilitar retiros
          </p>
        </div>
      </div>

      {error && (
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl p-6 mb-6">
          <div className="flex items-center gap-2">
            <AlertCircle className="w-5 h-5 text-red-500" />
            <p className="text-red-600 dark:text-red-400">{error}</p>
          </div>
        </div>
      )}

      <KYCVerificationPanel
        status={kycData.status}
        personalData={kycData.personalData}
        documents={kycData.documents}
        rejectionReason={kycData.rejectionReason}
        onSubmit={handleSubmit}
        onCancel={() => navigate('/investment/portfolio')}
      />
    </div>
  );
};

export default KYCVerification;
