"use client"

import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { X, Send, Building2, User, Mail, Phone, Users, AlertTriangle, CheckCircle } from 'lucide-react'
import CustomSelect from '@/components/ui/custom-select'

interface TeklifModalProps {
  isOpen: boolean
  onClose: () => void
  // Ön doldurulmuş değerler (hesaplayıcıdan)
  prefillData?: {
    tehlikeSinifi?: string
    calisanSayisi?: number
    hekimSuresi?: number
    uzmanSuresi?: number
    dspSuresi?: number
    hizmetTuru?: string
  }
}

const tehlikeSiniflari = [
  { value: 'az_tehlikeli', label: 'Az Tehlikeli' },
  { value: 'tehlikeli', label: 'Tehlikeli' },
  { value: 'cok_tehlikeli', label: 'Çok Tehlikeli' },
]

const hizmetler = [
  { id: 'isyeri_hekimligi', label: 'İşyeri Hekimliği' },
  { id: 'is_guvenligi', label: 'İş Güvenliği Uzmanlığı' },
  { id: 'dsp', label: 'Diğer Sağlık Personeli' },
  { id: 'egitim', label: 'İSG Eğitimleri' },
  { id: 'risk_analizi', label: 'Risk Analizi' },
  { id: 'acil_durum', label: 'Acil Durum Planı' },
]

export default function TeklifModal({ isOpen, onClose, prefillData }: TeklifModalProps) {
  const [step, setStep] = useState(1)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [isSuccess, setIsSuccess] = useState(false)
  const [error, setError] = useState('')
  
  const [formData, setFormData] = useState({
    companyName: '',
    authorizedPerson: '',
    email: '',
    phone: '',
    employeeCount: prefillData?.calisanSayisi?.toString() || '',
    tehlikeSinifi: prefillData?.tehlikeSinifi || '',
    naceCode: '',
    city: '',
    selectedServices: prefillData?.hizmetTuru ? [prefillData.hizmetTuru] : [] as string[],
    notes: '',
  })


  const toggleService = (id: string) => {
    setFormData(prev => ({
      ...prev,
      selectedServices: prev.selectedServices.includes(id)
        ? prev.selectedServices.filter(s => s !== id)
        : [...prev.selectedServices, id]
    }))
  }

  const handleSubmit = async () => {
    setError('')
    setIsSubmitting(true)

    try {
      const response = await fetch('/api/teklif-talebi', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          companyName: formData.companyName,
          authorizedPerson: formData.authorizedPerson,
          email: formData.email,
          phone: formData.phone,
          employeeCount: formData.employeeCount,
          tehlikeSinifi: formData.tehlikeSinifi,
          naceCode: formData.naceCode,
          city: formData.city,
          requestedServices: formData.selectedServices,
          notes: formData.notes,
          hekimSuresi: prefillData?.hekimSuresi,
          uzmanSuresi: prefillData?.uzmanSuresi,
          dspSuresi: prefillData?.dspSuresi,
        }),
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error || 'Bir hata oluştu')
      }

      setIsSuccess(true)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Bir hata oluştu')
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleClose = () => {
    setStep(1)
    setIsSuccess(false)
    setError('')
    onClose()
  }

  if (!isOpen) return null

  return (
    <AnimatePresence>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4"
        onClick={handleClose}
      >
        <motion.div
          initial={{ scale: 0.95, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          exit={{ scale: 0.95, opacity: 0 }}
          onClick={(e) => e.stopPropagation()}
          className="bg-white rounded-2xl w-full max-w-lg max-h-[90vh] overflow-hidden shadow-2xl"
        >
          {/* Header */}
          <div className="bg-gradient-to-r from-[#0F2A44] to-[#1a3a5c] p-5 text-white">
            <div className="flex items-center justify-between">
              <div>
                <h2 className="text-xl font-bold">Hemen Teklif Alın</h2>
                <p className="text-white/70 text-sm mt-1">Bilgilerinizi doldurun, size ulaşalım</p>
              </div>
              <button onClick={handleClose} className="p-2 hover:bg-white/10 rounded-lg transition-colors">
                <X className="w-5 h-5" />
              </button>
            </div>
            {/* Progress */}
            {!isSuccess && (
              <div className="flex gap-2 mt-4">
                {[1, 2].map((s) => (
                  <div key={s} className={`flex-1 h-1 rounded-full ${step >= s ? 'bg-white' : 'bg-white/30'}`} />
                ))}
              </div>
            )}
          </div>


          {/* Content */}
          <div className="p-5 overflow-y-auto max-h-[60vh]">
            {isSuccess ? (
              <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="text-center py-8">
                <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                  <CheckCircle className="w-8 h-8 text-green-600" />
                </div>
                <h3 className="text-xl font-bold text-[#0F2A44] mb-2">Talebiniz Alındı!</h3>
                <p className="text-gray-500 mb-6">En kısa sürede sizinle iletişime geçeceğiz.</p>
                <button onClick={handleClose} className="px-6 py-3 bg-[#0F2A44] text-white rounded-xl font-medium hover:bg-[#1a3a5c] transition-colors">
                  Tamam
                </button>
              </motion.div>
            ) : step === 1 ? (
              <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Şirket Adı *</label>
                  <div className="relative">
                    <Building2 className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                    <input type="text" value={formData.companyName} onChange={(e) => setFormData({...formData, companyName: e.target.value})}
                      className="w-full pl-10 pr-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0F2A44]/20 focus:border-[#0F2A44]" placeholder="Şirket adı" required />
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Yetkili Kişi *</label>
                  <div className="relative">
                    <User className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                    <input type="text" value={formData.authorizedPerson} onChange={(e) => setFormData({...formData, authorizedPerson: e.target.value})}
                      className="w-full pl-10 pr-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0F2A44]/20 focus:border-[#0F2A44]" placeholder="Ad Soyad" required />
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">E-posta *</label>
                    <div className="relative">
                      <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                      <input type="email" value={formData.email} onChange={(e) => setFormData({...formData, email: e.target.value})}
                        className="w-full pl-10 pr-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0F2A44]/20 focus:border-[#0F2A44]" placeholder="E-posta" required />
                    </div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Telefon *</label>
                    <div className="relative">
                      <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                      <input type="tel" value={formData.phone} onChange={(e) => setFormData({...formData, phone: e.target.value})}
                        className="w-full pl-10 pr-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0F2A44]/20 focus:border-[#0F2A44]" placeholder="05XX XXX XX XX" required />
                    </div>
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Şehir</label>
                  <input type="text" value={formData.city} onChange={(e) => setFormData({...formData, city: e.target.value})}
                    className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0F2A44]/20 focus:border-[#0F2A44]" placeholder="İstanbul" />
                </div>
              </motion.div>
            ) : (
              <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Çalışan Sayısı *</label>
                    <div className="relative">
                      <Users className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                      <input type="number" value={formData.employeeCount} onChange={(e) => setFormData({...formData, employeeCount: e.target.value})}
                        className="w-full pl-10 pr-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0F2A44]/20 focus:border-[#0F2A44]" placeholder="Çalışan sayısı" required min="1" />
                    </div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Tehlike Sınıfı</label>
                    <CustomSelect
                      name="tehlikeSinifi"
                      value={formData.tehlikeSinifi}
                      onChange={(e) => setFormData({...formData, tehlikeSinifi: e.target.value})}
                      placeholder="Seçiniz"
                      variant="admin"
                      icon={<AlertTriangle className="w-5 h-5 text-gray-400" />}
                      options={tehlikeSiniflari}
                    />
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">NACE Kodu (Opsiyonel)</label>
                  <input type="text" value={formData.naceCode} onChange={(e) => setFormData({...formData, naceCode: e.target.value})}
                    className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0F2A44]/20 focus:border-[#0F2A44]" placeholder="Örn: 10.11.01" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Talep Edilen Hizmetler</label>
                  <div className="grid grid-cols-2 gap-2">
                    {hizmetler.map(h => (
                      <label key={h.id} className={`flex items-center gap-2 p-3 rounded-lg border cursor-pointer transition-all text-sm ${
                        formData.selectedServices.includes(h.id) ? 'border-[#0F2A44] bg-[#0F2A44]/5' : 'border-gray-200 hover:border-gray-300'
                      }`}>
                        <input type="checkbox" checked={formData.selectedServices.includes(h.id)} onChange={() => toggleService(h.id)} className="sr-only" />
                        <div className={`w-4 h-4 rounded border-2 flex items-center justify-center ${
                          formData.selectedServices.includes(h.id) ? 'border-[#0F2A44] bg-[#0F2A44]' : 'border-gray-300'
                        }`}>
                          {formData.selectedServices.includes(h.id) && (
                            <svg className="w-2.5 h-2.5 text-white" fill="currentColor" viewBox="0 0 20 20">
                              <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                            </svg>
                          )}
                        </div>
                        <span className="text-gray-700">{h.label}</span>
                      </label>
                    ))}
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Ek Notlar</label>
                  <textarea value={formData.notes} onChange={(e) => setFormData({...formData, notes: e.target.value})} rows={2}
                    className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0F2A44]/20 focus:border-[#0F2A44] resize-none" placeholder="Varsa eklemek istediğiniz notlar..." />
                </div>
                {error && <p className="text-red-500 text-sm">{error}</p>}
              </motion.div>
            )}
          </div>


          {/* Footer */}
          {!isSuccess && (
            <div className="p-5 border-t border-gray-100 flex gap-3">
              {step === 2 && (
                <button onClick={() => setStep(1)} className="flex-1 px-4 py-3 border border-gray-200 text-gray-700 rounded-xl font-medium hover:bg-gray-50 transition-colors">
                  Geri
                </button>
              )}
              {step === 1 ? (
                <button onClick={() => setStep(2)} disabled={!formData.companyName || !formData.authorizedPerson || !formData.email || !formData.phone}
                  className="flex-1 px-4 py-3 bg-[#0F2A44] text-white rounded-xl font-medium hover:bg-[#1a3a5c] disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors">
                  Devam Et
                </button>
              ) : (
                <button onClick={handleSubmit} disabled={isSubmitting || !formData.employeeCount}
                  className="flex-1 px-4 py-3 bg-[#C8102E] text-white rounded-xl font-medium hover:bg-[#a50d26] disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2">
                  {isSubmitting ? (
                    <><svg className="animate-spin h-5 w-5" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" /><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" /></svg>Gönderiliyor...</>
                  ) : (
                    <><Send className="w-5 h-5" />Teklif Talep Et</>
                  )}
                </button>
              )}
            </div>
          )}
        </motion.div>
      </motion.div>
    </AnimatePresence>
  )
}