import { useState, useEffect } from "react";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { StatCards } from "./organisms/StatCards";
import { SearchFilter } from "./organisms/SearchFilter";
import { DataTable, Column } from "./organisms/DataTable";
import { EmptyState } from "./organisms/EmptyState";
import { MobileCard } from "./organisms/MobileCard";
import { Button } from "./ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "./ui/dialog";
import { Label } from "./ui/label";
import { Input } from "./ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { 
  Users, 
  Mail, 
  Phone, 
  Building2, 
  CheckCircle2,
  Clock,
  Send,
  Sparkles,
  Copy,
  ExternalLink
} from "lucide-react";
import { toast } from "sonner";

interface Lead {
  id: string;
  name: string;
  company: string;
  email: string;
  phone: string;
  industry: string;
  message: string;
  status: "pending" | "contacted" | "demo-sent";
  submittedAt: string;
  demoLink?: string;
  demoExpiryDate?: string;
  industryPreset?: string;
  demoDuration?: number;
}

interface SalesLeadDashboardProps {
  onBackToLanding?: () => void;
  onStartDemo?: (config: any) => void;
}

export function SalesLeadDashboard({ onBackToLanding, onStartDemo }: SalesLeadDashboardProps = {}) {
  const [searchTerm, setSearchTerm] = useState("");
  const [filterStatus, setFilterStatus] = useState("all");
  const [selectedLead, setSelectedLead] = useState<Lead | null>(null);
  const [isCreateDemoOpen, setIsCreateDemoOpen] = useState(false);
  const [isDetailOpen, setIsDetailOpen] = useState(false);
  
  // Demo 생성 폼 데이터
  const [industryPreset, setIndustryPreset] = useState("");
  const [demoDuration, setDemoDuration] = useState("7");
  const [generatedLink, setGeneratedLink] = useState("");
  const [isCopied, setIsCopied] = useState(false);

  // 샘플 리드 데이터
  const [leads, setLeads] = useState<Lead[]>([
    {
      id: "1",
      name: "김철수",
      company: "테크솔루션",
      email: "kim@techsol.com",
      phone: "010-1234-5678",
      industry: "전자제품",
      message: "자동차 부품 제조 MES 시스템 문의드립니다",
      status: "pending",
      submittedAt: "2025-10-24T09:00:00"
    },
    {
      id: "2",
      name: "이영희",
      company: "스마트팩토리",
      email: "lee@smartfactory.com",
      phone: "010-2345-6789",
      industry: "기계부품",
      message: "생산 관리 시스템 도입 검토 중입니다",
      status: "contacted",
      submittedAt: "2025-10-23T14:30:00"
    },
    {
      id: "3",
      name: "박민수",
      company: "글로벌제조",
      email: "park@global.com",
      phone: "010-3456-7890",
      industry: "플라스틱",
      message: "데모 체험 후 도입 고려 중",
      status: "demo-sent",
      submittedAt: "2025-10-22T11:15:00",
      demoLink: "https://sam.example.com/demo/xyz123",
      demoExpiryDate: "2025-10-29T11:15:00"
    }
  ]);

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

  const loadLeads = () => {
    const storedLeads = JSON.parse(localStorage.getItem("salesLeads") || "[]");
    if (storedLeads.length > 0) {
      setLeads(storedLeads);
    }
  };

  const stats = [
    {
      label: "전체 리드",
      value: leads.length,
      icon: Users,
      iconColor: "text-blue-600"
    },
    {
      label: "대기중",
      value: leads.filter(l => l.status === "pending").length,
      icon: Clock,
      iconColor: "text-yellow-600"
    },
    {
      label: "연락완료",
      value: leads.filter(l => l.status === "contacted").length,
      icon: Phone,
      iconColor: "text-green-600"
    },
    {
      label: "데모발송",
      value: leads.filter(l => l.status === "demo-sent").length,
      icon: CheckCircle2,
      iconColor: "text-purple-600"
    }
  ];

  const filteredLeads = leads.filter(lead => {
    const matchesSearch = 
      lead.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      lead.company.toLowerCase().includes(searchTerm.toLowerCase()) ||
      lead.email.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesStatus = filterStatus === "all" || lead.status === filterStatus;
    
    return matchesSearch && matchesStatus;
  });

  const columns: Column<Lead>[] = [
    { 
      key: "name", 
      label: "이름",
      type: "text"
    },
    { 
      key: "company", 
      label: "회사",
      type: "text"
    },
    { 
      key: "industry", 
      label: "업종",
      type: "badge",
      badgeConfig: { variant: "outline" }
    },
    { 
      key: "email", 
      label: "이메일",
      type: "text"
    },
    { 
      key: "phone", 
      label: "연락처",
      type: "text"
    },
    { 
      key: "status", 
      label: "상태",
      type: "status",
      render: (value) => {
        switch (value) {
          case "pending": return "대기";
          case "contacted": return "연락완료";
          case "demo-sent": return "데모발송";
          default: return value;
        }
      }
    },
    { 
      key: "submittedAt", 
      label: "문의일",
      type: "datetime"
    },
    {
      key: "id",
      label: "관리",
      type: "actions",
      render: (_, row) => [
        { type: "view", onClick: () => handleViewDetail(row) },
        { 
          type: "custom",
          label: "데모생성",
          icon: Sparkles,
          onClick: () => handleCreateDemo(row),
          hidden: row.status === "demo-sent"
        },
        {
          type: "custom",
          label: "데모열기",
          icon: ExternalLink,
          onClick: () => handleOpenDemo(row),
          hidden: row.status !== "demo-sent"
        }
      ]
    }
  ];

  const handleViewDetail = (lead: Lead) => {
    setSelectedLead(lead);
    setIsDetailOpen(true);
  };

  const handleCreateDemo = (lead: Lead) => {
    setSelectedLead(lead);
    setIndustryPreset(lead.industry || "");
    setIsCreateDemoOpen(true);
    setGeneratedLink("");
    setIsCopied(false);
  };

  const handleGenerateLink = () => {
    if (!selectedLead) return;

    const demoId = `demo_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const expiryDate = new Date();
    expiryDate.setDate(expiryDate.getDate() + parseInt(demoDuration));
    
    const demoLink = `${window.location.origin}/#/demo/${demoId}`;
    
    // Demo 설정 저장
    const demoConfig = {
      demoId,
      leadId: selectedLead.id,
      industryPreset,
      demoDuration: parseInt(demoDuration),
      expiryDate: expiryDate.toISOString(),
      createdAt: new Date().toISOString(),
      clientEmail: selectedLead.email,
      clientName: selectedLead.name,
      company: selectedLead.company,
    };
    
    // localStorage에 demo 설정 저장
    const existingDemos = JSON.parse(localStorage.getItem("demoConfigs") || "{}");
    existingDemos[demoId] = demoConfig;
    localStorage.setItem("demoConfigs", JSON.stringify(existingDemos));
    
    // Lead 상태 업데이트
    const updatedLeads = leads.map(l => 
      l.id === selectedLead.id 
        ? { 
            ...l, 
            status: "demo-sent" as const, 
            demoLink,
            demoExpiryDate: expiryDate.toISOString(),
            industryPreset,
            demoDuration: parseInt(demoDuration)
          }
        : l
    );
    setLeads(updatedLeads);
    localStorage.setItem("salesLeads", JSON.stringify(updatedLeads));
    
    setGeneratedLink(demoLink);
    
    toast.success("데모 링크가 생성되었습니다!", {
      description: `${selectedLead.email}로 이메일을 전송할 수 있습니다.`,
    });
  };

  const handleCopyLink = () => {
    if (!generatedLink) return;
    
    navigator.clipboard.writeText(generatedLink).then(() => {
      setIsCopied(true);
      toast.success("링크가 클립보드에 복사되었습니다!");
      setTimeout(() => setIsCopied(false), 2000);
    }).catch(() => {
      toast.error("링크 복사에 실패했습니다.");
    });
  };

  const handleSendEmail = () => {
    if (!selectedLead || !generatedLink) return;
    
    const subject = encodeURIComponent(`[SAM] ${selectedLead.company} 맞춤형 데모 링크`);
    const body = encodeURIComponent(
      `안녕하세요 ${selectedLead.name}님,\n\n` +
      `${selectedLead.company}의 ${industryPreset} 산업 환경에 최적화된 SAM MES 데모를 준비했습니다.\n\n` +
      `아래 링크를 통해 ${demoDuration}일간 무료로 체험하실 수 있습니다:\n` +
      `${generatedLink}\n\n` +
      `감사합니다.\n` +
      `SAM 영업팀`
    );
    
    window.open(`mailto:${selectedLead.email}?subject=${subject}&body=${body}`);
    
    toast.success("이메일 클라이언트가 열렸습니다!");
  };

  const handleOpenDemo = (lead: Lead) => {
    const demoConfigs = JSON.parse(localStorage.getItem("demoConfigs") || "{}");
    const demoId = lead.demoLink?.split("/demo/")[1];
    
    if (demoId && demoConfigs[demoId] && onStartDemo) {
      onStartDemo(demoConfigs[demoId]);
      toast.success(`${lead.company}의 데모를 시작합니다.`);
    } else {
      window.open(lead.demoLink, "_blank");
    }
  };

  const handleUpdateStatus = (status: Lead["status"]) => {
    if (!selectedLead) return;
    
    const updatedLeads = leads.map(l =>
      l.id === selectedLead.id ? { ...l, status } : l
    );
    setLeads(updatedLeads);
    localStorage.setItem("salesLeads", JSON.stringify(updatedLeads));
    setSelectedLead({ ...selectedLead, status });
    
    const statusLabels = {
      pending: "대기",
      contacted: "연락완료",
      "demo-sent": "데모발송"
    };
    
    toast.success(`상태가 '${statusLabels[status]}'로 변경되었습니다.`);
  };

  return (
    <PageLayout>
      <PageHeader
        title="리드 관리"
        description="영업 리드를 관리하고 데모를 생성합니다"
        icon={Users}
        actions={
          onBackToLanding && (
            <Button variant="outline" onClick={onBackToLanding}>
              랜딩페이지로
            </Button>
          )
        }
      />

      <StatCards stats={stats} />

      <SearchFilter
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="이름, 회사명, 이메일로 검색..."
        filters={
          <Select value={filterStatus} onValueChange={setFilterStatus}>
            <SelectTrigger className="w-full md:w-[200px]">
              <SelectValue placeholder="상태 필터" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체</SelectItem>
              <SelectItem value="pending">대기중</SelectItem>
              <SelectItem value="contacted">연락완료</SelectItem>
              <SelectItem value="demo-sent">데모발송</SelectItem>
            </SelectContent>
          </Select>
        }
      />

      {filteredLeads.length === 0 ? (
        <EmptyState
          icon={Users}
          title="등록된 리드가 없습니다"
          description="랜딩 페이지에서 데모를 신청하면 이곳에 표시됩니다"
        />
      ) : (
        <>
          <DataTable
            columns={columns}
            data={filteredLeads}
            keyField="id"
            onRowClick={handleViewDetail}
          />

          <div className="md:hidden space-y-3">
            {filteredLeads.map((lead) => (
              <MobileCard
                key={lead.id}
                title={lead.name}
                subtitle={lead.company}
                icon={<Users className="w-4 h-4 text-blue-600" />}
                badge={{
                  label: lead.status === "pending" ? "대기" : lead.status === "contacted" ? "연락완료" : "데모발송",
                  variant: lead.status === "demo-sent" ? "default" : "secondary"
                }}
                fields={[
                  { label: "이메일", value: lead.email },
                  { label: "연락처", value: lead.phone },
                  { label: "업종", value: lead.industry },
                  { label: "문의일", value: new Date(lead.submittedAt).toLocaleDateString() }
                ]}
                actions={[
                  {
                    label: "상세",
                    onClick: () => handleViewDetail(lead),
                    variant: "outline"
                  },
                  lead.status !== "demo-sent" ? {
                    label: "데모생성",
                    onClick: () => handleCreateDemo(lead),
                    icon: Sparkles,
                    variant: "default"
                  } : {
                    label: "데모열기",
                    onClick: () => handleOpenDemo(lead),
                    icon: ExternalLink,
                    variant: "default"
                  }
                ]}
              />
            ))}
          </div>
        </>
      )}

      {/* 상세 보기 다이얼로그 */}
      <Dialog open={isDetailOpen} onOpenChange={setIsDetailOpen}>
        <DialogContent className="max-w-[95vw] sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>리드 상세</DialogTitle>
            <DialogDescription>
              {selectedLead?.name} - {selectedLead?.company}
            </DialogDescription>
          </DialogHeader>

          {selectedLead && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="text-muted-foreground">이름:</span>
                  <p className="font-medium mt-1">{selectedLead.name}</p>
                </div>
                <div>
                  <span className="text-muted-foreground">회사:</span>
                  <p className="font-medium mt-1">{selectedLead.company}</p>
                </div>
                <div>
                  <span className="text-muted-foreground">이메일:</span>
                  <p className="font-medium mt-1">{selectedLead.email}</p>
                </div>
                <div>
                  <span className="text-muted-foreground">연락처:</span>
                  <p className="font-medium mt-1">{selectedLead.phone}</p>
                </div>
                <div>
                  <span className="text-muted-foreground">업종:</span>
                  <p className="font-medium mt-1">{selectedLead.industry}</p>
                </div>
                <div>
                  <span className="text-muted-foreground">문의일:</span>
                  <p className="font-medium mt-1">
                    {new Date(selectedLead.submittedAt).toLocaleString()}
                  </p>
                </div>
              </div>

              <div>
                <span className="text-muted-foreground text-sm">문의내용:</span>
                <p className="mt-1 p-3 bg-muted rounded-lg text-sm">{selectedLead.message}</p>
              </div>

              <div>
                <span className="text-muted-foreground text-sm">상태 변경:</span>
                <div className="flex gap-2 mt-2">
                  <Button 
                    size="sm" 
                    variant={selectedLead.status === "pending" ? "default" : "outline"}
                    onClick={() => handleUpdateStatus("pending")}
                  >
                    대기
                  </Button>
                  <Button 
                    size="sm"
                    variant={selectedLead.status === "contacted" ? "default" : "outline"}
                    onClick={() => handleUpdateStatus("contacted")}
                  >
                    연락완료
                  </Button>
                  <Button 
                    size="sm"
                    variant={selectedLead.status === "demo-sent" ? "default" : "outline"}
                    onClick={() => handleUpdateStatus("demo-sent")}
                  >
                    데모발송
                  </Button>
                </div>
              </div>

              {selectedLead.demoLink && (
                <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                  <p className="text-sm font-medium text-blue-900 mb-1">데모 링크</p>
                  <p className="text-xs text-blue-700 break-all">{selectedLead.demoLink}</p>
                  <p className="text-xs text-blue-600 mt-1">
                    만료일: {selectedLead.demoExpiryDate && new Date(selectedLead.demoExpiryDate).toLocaleDateString()}
                  </p>
                </div>
              )}
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setIsDetailOpen(false)}>
              닫기
            </Button>
            {selectedLead && selectedLead.status !== "demo-sent" && (
              <Button onClick={() => {
                setIsDetailOpen(false);
                handleCreateDemo(selectedLead);
              }}>
                <Sparkles className="w-4 h-4 mr-2" />
                데모 생성
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 데모 생성 다이얼로그 */}
      <Dialog open={isCreateDemoOpen} onOpenChange={setIsCreateDemoOpen}>
        <DialogContent className="max-w-[95vw] sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>맞춤형 데모 생성</DialogTitle>
            <DialogDescription>
              {selectedLead?.company}를 위한 데모 환경을 설정합니다
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div>
              <Label>고객 정보</Label>
              <div className="mt-2 p-3 bg-muted rounded-lg text-sm">
                <p><strong>{selectedLead?.name}</strong> - {selectedLead?.company}</p>
                <p className="text-muted-foreground">{selectedLead?.email}</p>
              </div>
            </div>

            <div>
              <Label>업종 프리셋</Label>
              <Select value={industryPreset} onValueChange={setIndustryPreset}>
                <SelectTrigger>
                  <SelectValue placeholder="업종 선택" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="전자제품">전자제품</SelectItem>
                  <SelectItem value="자동차부품">자동차부품</SelectItem>
                  <SelectItem value="기계부품">기계부품</SelectItem>
                  <SelectItem value="플라스틱">플라스틱</SelectItem>
                  <SelectItem value="금속가공">금속가공</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>데모 기간</Label>
              <Select value={demoDuration} onValueChange={setDemoDuration}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="7">7일</SelectItem>
                  <SelectItem value="14">14일</SelectItem>
                  <SelectItem value="30">30일</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {!generatedLink ? (
              <Button className="w-full" onClick={handleGenerateLink}>
                <Sparkles className="w-4 h-4 mr-2" />
                데모 링크 생성
              </Button>
            ) : (
              <div className="space-y-3">
                <div className="p-3 bg-green-50 border border-green-200 rounded-lg">
                  <p className="text-sm font-medium text-green-900 mb-2">데모 링크가 생성되었습니다!</p>
                  <p className="text-xs text-green-700 break-all mb-3">{generatedLink}</p>
                  <div className="flex gap-2">
                    <Button size="sm" variant="outline" className="flex-1" onClick={handleCopyLink}>
                      {isCopied ? <CheckCircle2 className="w-4 h-4 mr-2" /> : <Copy className="w-4 h-4 mr-2" />}
                      {isCopied ? "복사됨" : "복사"}
                    </Button>
                    <Button size="sm" className="flex-1" onClick={handleSendEmail}>
                      <Send className="w-4 h-4 mr-2" />
                      이메일 전송
                    </Button>
                  </div>
                </div>
              </div>
            )}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setIsCreateDemoOpen(false);
              setGeneratedLink("");
            }}>
              {generatedLink ? "완료" : "취소"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </PageLayout>
  );
}
