import { useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "./ui/dialog";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Building2, Mail, Phone, Briefcase, MessageSquare } from "lucide-react";

interface ContactModalProps {
  isOpen: boolean;
  onClose: () => void;
  title?: string;
  description?: string;
}

export function ContactModal({ isOpen, onClose, title, description }: ContactModalProps) {
  const [formData, setFormData] = useState({
    name: "",
    company: "",
    email: "",
    phone: "",
    industry: "",
    message: ""
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    // localStorage에 리드 저장
    const leadId = `lead_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const newLead = {
      id: leadId,
      ...formData,
      status: "pending",
      submittedAt: new Date().toISOString(),
    };
    
    const existingLeads = JSON.parse(localStorage.getItem("salesLeads") || "[]");
    existingLeads.push(newLead);
    localStorage.setItem("salesLeads", JSON.stringify(existingLeads));
    
    console.log("Form submitted:", formData);
    alert("데모 요청이 접수되었습니다. 1영업일 내에 연락드리겠습니다.");
    onClose();
    
    // 폼 초기화
    setFormData({
      name: "",
      company: "",
      email: "",
      phone: "",
      industry: "",
      message: ""
    });
  };

  const handleChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="text-2xl font-bold">
            {title || "데모 요청하기"}
          </DialogTitle>
          <DialogDescription className="text-base">
            {description || "귀사의 정보를 입력해주시면 전문 영업사원이 1영업일 내에 연락드립니다."}
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-6 mt-4">
          {/* 이름 */}
          <div className="space-y-2">
            <Label htmlFor="name" className="text-sm font-semibold flex items-center gap-2">
              <Building2 className="w-4 h-4 text-blue-600" />
              담당자 성함 *
            </Label>
            <Input
              id="name"
              placeholder="홍길동"
              value={formData.name}
              onChange={(e) => handleChange("name", e.target.value)}
              required
              className="h-11"
            />
          </div>

          {/* 회사명 */}
          <div className="space-y-2">
            <Label htmlFor="company" className="text-sm font-semibold flex items-center gap-2">
              <Building2 className="w-4 h-4 text-blue-600" />
              회사명 *
            </Label>
            <Input
              id="company"
              placeholder="(주)샘플컴퍼니"
              value={formData.company}
              onChange={(e) => handleChange("company", e.target.value)}
              required
              className="h-11"
            />
          </div>

          {/* 이메일 & 연락처 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="email" className="text-sm font-semibold flex items-center gap-2">
                <Mail className="w-4 h-4 text-blue-600" />
                이메일 *
              </Label>
              <Input
                id="email"
                type="email"
                placeholder="contact@company.com"
                value={formData.email}
                onChange={(e) => handleChange("email", e.target.value)}
                required
                className="h-11"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="phone" className="text-sm font-semibold flex items-center gap-2">
                <Phone className="w-4 h-4 text-blue-600" />
                연락처 *
              </Label>
              <Input
                id="phone"
                type="tel"
                placeholder="010-1234-5678"
                value={formData.phone}
                onChange={(e) => handleChange("phone", e.target.value)}
                required
                className="h-11"
              />
            </div>
          </div>

          {/* 산업 분야 */}
          <div className="space-y-2">
            <Label htmlFor="industry" className="text-sm font-semibold flex items-center gap-2">
              <Briefcase className="w-4 h-4 text-blue-600" />
              산업 분야 *
            </Label>
            <Select value={formData.industry} onValueChange={(value) => handleChange("industry", value)} required>
              <SelectTrigger className="h-11">
                <SelectValue placeholder="산업 분야를 선택해주세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="automotive">자동차 부품</SelectItem>
                <SelectItem value="electronics">전자/전기</SelectItem>
                <SelectItem value="machinery">기계/설비</SelectItem>
                <SelectItem value="food">식품 가공</SelectItem>
                <SelectItem value="chemical">화학/제약</SelectItem>
                <SelectItem value="plastic">플라스틱/고무</SelectItem>
                <SelectItem value="metal">금속 가공</SelectItem>
                <SelectItem value="other">기타</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 요청사항 */}
          <div className="space-y-2">
            <Label htmlFor="message" className="text-sm font-semibold flex items-center gap-2">
              <MessageSquare className="w-4 h-4 text-blue-600" />
              요청사항 (선택)
            </Label>
            <Textarea
              id="message"
              placeholder="궁금하신 점이나 특별히 보고 싶은 기능이 있으시면 작성해주세요."
              value={formData.message}
              onChange={(e) => handleChange("message", e.target.value)}
              rows={4}
              className="resize-none"
            />
          </div>

          {/* 버튼 */}
          <div className="flex flex-col-reverse sm:flex-row gap-3 pt-4">
            <Button
              type="button"
              variant="outline"
              onClick={onClose}
              className="flex-1 h-12"
            >
              취소
            </Button>
            <Button
              type="submit"
              className="flex-1 h-12 bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white font-semibold"
            >
              데모 요청하기
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
