import { useState } from 'react';
import { Steps, Card, message, Row, Col } from 'antd';
import Step1Policy from '../components/form/Step1Policy';
import Step2Details from '../components/form/Step2Details';
import Step3Payment from '../components/form/Step3Payment';
import DebugPanel from '../components/DebugPanel';
import './ClaimForm.css';

const { Step } = Steps;

interface FormData {
  // Шаг 1
  voucher: string;  // Полис вида E1000-302538524
  email: string;     // Email обязателен
  
  // Шаг 2
  incidentDate?: string;
  incidentDescription?: string;
  transportType?: string;
  uploadedFiles?: string[];
  
  // Шаг 3
  phone: string;
  paymentMethod: string;
  bankName?: string;
  cardNumber?: string;
  accountNumber?: string;
}

export default function ClaimForm() {
  // Генерируем claim_id один раз при загрузке формы
  const [claimId] = useState(() => {
    const date = new Date().toISOString().split('T')[0];
    const randomId = Math.random().toString(36).substr(2, 6).toUpperCase();
    return `CLM-${date}-${randomId}`;
  });

  // Генерируем session_id и сохраняем в sessionStorage
  const [sessionId] = useState(() => {
    let sid = sessionStorage.getItem('session_id');
    if (!sid) {
      sid = `sess-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
      sessionStorage.setItem('session_id', sid);
    }
    return sid;
  });

  const [currentStep, setCurrentStep] = useState(0);
  const [formData, setFormData] = useState<FormData>({
    voucher: '',
    email: '',
    phone: '',
    paymentMethod: 'sbp',
  });
  const [isPhoneVerified, setIsPhoneVerified] = useState(false);
  const [debugEvents, setDebugEvents] = useState<any[]>([]);

  const addDebugEvent = (type: string, status: string, message: string, data?: any) => {
    const event = {
      timestamp: new Date().toLocaleTimeString('ru-RU'),
      type,
      status,
      message,
      data: {
        ...data,
        claim_id: claimId  // Добавляем claim_id во все события
      }
    };
    setDebugEvents(prev => [event, ...prev]);
  };

  // Логируем генерацию claim_id и session_id при первой загрузке
  useState(() => {
    addDebugEvent('system', 'info', `🆔 Сгенерирован Claim ID: ${claimId}`, {
      claim_id: claimId,
      session_id: sessionId,
      timestamp: new Date().toISOString()
    });
  });

  const updateFormData = (data: Partial<FormData>) => {
    setFormData({ ...formData, ...data });
  };

  const nextStep = () => {
    setCurrentStep(currentStep + 1);
  };

  const prevStep = () => {
    setCurrentStep(currentStep - 1);
  };

  const handleSubmit = async () => {
    try {
      const response = await fetch('http://147.45.146.17:8100/api/v1/claims/create', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          voucher: formData.voucher,
          email: formData.email,
          phone: formData.phone,
          incident_date: formData.incidentDate,
          incident_description: formData.incidentDescription,
          transport_type: formData.transportType,
          payment_method: formData.paymentMethod,
          bank_name: formData.bankName,
          card_number: formData.cardNumber,
          account_number: formData.accountNumber,
          uploaded_files: formData.uploadedFiles || [],
        }),
      });

      const result = await response.json();

      if (result.success) {
        message.success(`Заявка ${result.claim_number} успешно создана!`);
        // Сброс формы
        setFormData({
          voucher: '',
          email: '',
          phone: '',
          paymentMethod: 'sbp',
        });
        setCurrentStep(0);
        setIsPhoneVerified(false);
      } else {
        message.error('Ошибка при создании заявки');
      }
    } catch (error) {
      message.error('Ошибка соединения с сервером');
      console.error(error);
    }
  };

  const steps = [
    {
      title: 'Проверка полиса',
      content: (
        <Step1Policy 
          formData={{ ...formData, claim_id: claimId }}
          updateFormData={updateFormData} 
          onNext={nextStep}
          addDebugEvent={addDebugEvent}
        />
      ),
    },
    {
      title: 'Детали происшествия',
      content: (
        <Step2Details
          formData={{ ...formData, claim_id: claimId }}
          updateFormData={updateFormData}
          onNext={nextStep}
          onPrev={prevStep}
          addDebugEvent={addDebugEvent}
        />
      ),
    },
    {
      title: 'Телефон и выплата',
      content: (
        <Step3Payment
          formData={{ ...formData, claim_id: claimId }}
          updateFormData={updateFormData}
          onPrev={prevStep}
          onSubmit={handleSubmit}
          isPhoneVerified={isPhoneVerified}
          setIsPhoneVerified={setIsPhoneVerified}
          addDebugEvent={addDebugEvent}
        />
      ),
    },
  ];

  const handleReset = () => {
    setFormData({
      voucher: '',
      email: '',
      phone: '',
      paymentMethod: 'sbp',
    });
    setCurrentStep(0);
    setIsPhoneVerified(false);
    message.info('Форма сброшена');
  };

  return (
    <div className="claim-form-container" style={{ padding: '20px', background: '#f0f2f5' }}>
      <Row gutter={16}>
        {/* Левая часть - Форма */}
        <Col xs={24} lg={14}>
          <Card 
            title="Подать заявку на выплату" 
            className="claim-form-card"
            extra={
              currentStep > 0 && (
                <button 
                  onClick={handleReset}
                  style={{
                    padding: '4px 12px',
                    background: '#fff',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    cursor: 'pointer',
                    fontSize: '14px'
                  }}
                >
                  🔄 Начать заново
                </button>
              )
            }
          >
            <Steps current={currentStep} className="steps">
              {steps.map((item) => (
                <Step key={item.title} title={item.title} />
              ))}
            </Steps>
            <div className="steps-content">{steps[currentStep].content}</div>
          </Card>
        </Col>

        {/* Правая часть - Debug консоль */}
        <Col xs={24} lg={10}>
          <DebugPanel events={debugEvents} formData={formData} />
        </Col>
      </Row>
    </div>
  );
}

