"use client";

import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Upload,
  Send,
  FileText,
  Users,
  AlertCircle,
  CheckCircle2,
  Loader2,
  Download,
  X,
} from "lucide-react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useToast } from "@/hooks/use-toast";
import {
  MailAccount,
  MailTemplate,
  getMailAccounts,
  getMailTemplates,
  sendBulkMail,
} from "@/lib/api/mail";

interface RecipientData {
  email: string;
  variables: Record<string, string>;
}

export default function BulkSendPage() {
  const router = useRouter();
  const { toast } = useToast();

  const [accounts, setAccounts] = useState<MailAccount[]>([]);
  const [templates, setTemplates] = useState<MailTemplate[]>([]);
  const [selectedAccountId, setSelectedAccountId] = useState<string>("");
  const [selectedTemplateId, setSelectedTemplateId] = useState<string>("");
  const [useTemplate, setUseTemplate] = useState<boolean>(true); // 템플릿 사용 여부
  const [customHtml, setCustomHtml] = useState<string>(""); // 직접 작성한 HTML
  const [subject, setSubject] = useState<string>("");
  const [recipients, setRecipients] = useState<RecipientData[]>([]);
  const [csvFile, setCsvFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(false);
  const [sending, setSending] = useState(false);
  const [sendProgress, setSendProgress] = useState({ sent: 0, total: 0 });

  useEffect(() => {
    loadAccounts();
    loadTemplates();
  }, []);

  const loadAccounts = async () => {
    try {
      const data = await getMailAccounts();
      setAccounts(data.filter((acc) => acc.status === 'active'));
    } catch (error: unknown) {
      const err = error as Error;
      toast({
        title: "계정 로드 실패",
        description: err.message,
        variant: "destructive",
      });
    }
  };

  const loadTemplates = async () => {
    try {
      const data = await getMailTemplates();
      setTemplates(data);
    } catch (error: unknown) {
      const err = error as Error;
      toast({
        title: "템플릿 로드 실패",
        description: err.message,
        variant: "destructive",
      });
    }
  };

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!file.name.endsWith(".csv")) {
      toast({
        title: "파일 형식 오류",
        description: "CSV 파일만 업로드 가능합니다.",
        variant: "destructive",
      });
      return;
    }

    setCsvFile(file);
    setLoading(true);

    try {
      const text = await file.text();
      const lines = text.split("\n").filter((line) => line.trim());
      
      if (lines.length < 2) {
        throw new Error("CSV 파일에 데이터가 없습니다.");
      }

      // 첫 줄은 헤더
      const headers = lines[0].split(",").map((h) => h.trim());
      
      if (!headers.includes("email")) {
        throw new Error("CSV 파일에 'email' 컬럼이 필요합니다.");
      }

      const emailIndex = headers.indexOf("email");
      const variableHeaders = headers.filter((h) => h !== "email");

      const parsedRecipients: RecipientData[] = lines.slice(1).map((line) => {
        const values = line.split(",").map((v) => v.trim());
        const email = values[emailIndex];
        const variables: Record<string, string> = {};

        variableHeaders.forEach((header, index) => {
          const valueIndex = headers.indexOf(header);
          variables[header] = values[valueIndex] || "";
        });

        return { email, variables };
      });

      setRecipients(parsedRecipients);
      toast({
        title: "파일 업로드 성공",
        description: `${parsedRecipients.length}명의 수신자를 불러왔습니다.`,
      });
    } catch (error: unknown) {
      const err = error as Error;
      toast({
        title: "파일 파싱 실패",
        description: err.message,
        variant: "destructive",
      });
      setCsvFile(null);
      setRecipients([]);
    } finally {
      setLoading(false);
    }
  };

  const handleSend = async () => {
    if (!selectedAccountId) {
      toast({
        title: "계정 선택 필요",
        description: "발송할 메일 계정을 선택해주세요.",
        variant: "destructive",
      });
      return;
    }

    // 템플릿 또는 직접 작성 중 하나는 있어야 함
    if (useTemplate && !selectedTemplateId) {
      toast({
        title: "템플릿 선택 필요",
        description: "사용할 템플릿을 선택해주세요.",
        variant: "destructive",
      });
      return;
    }

    if (!useTemplate && !customHtml.trim()) {
      toast({
        title: "내용 입력 필요",
        description: "메일 내용을 입력해주세요.",
        variant: "destructive",
      });
      return;
    }

    if (!subject.trim()) {
      toast({
        title: "제목 입력 필요",
        description: "메일 제목을 입력해주세요.",
        variant: "destructive",
      });
      return;
    }

    if (recipients.length === 0) {
      toast({
        title: "수신자 없음",
        description: "CSV 파일을 업로드해주세요.",
        variant: "destructive",
      });
      return;
    }

    setSending(true);
    setSendProgress({ sent: 0, total: recipients.length });

    try {
      await sendBulkMail({
        accountId: selectedAccountId,
        templateId: useTemplate ? selectedTemplateId : undefined,
        customHtml: !useTemplate ? customHtml : undefined,
        subject,
        recipients,
        onProgress: (sent, total) => {
          setSendProgress({ sent, total });
        },
      });

      toast({
        title: "대량 발송 완료",
        description: `${recipients.length}명에게 메일을 발송했습니다.`,
      });

      // 초기화
      setSelectedAccountId("");
      setSelectedTemplateId("");
      setSubject("");
      setRecipients([]);
      setCsvFile(null);
    } catch (error: unknown) {
      const err = error as Error;
      toast({
        title: "발송 실패",
        description: err.message,
        variant: "destructive",
      });
    } finally {
      setSending(false);
    }
  };

  const downloadSampleCsv = () => {
    const sample = `email,name,company
example1@example.com,홍길동,ABC회사
example2@example.com,김철수,XYZ회사`;

    const blob = new Blob([sample], { type: "text/csv;charset=utf-8;" });
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = "sample.csv";
    link.click();
  };

  return (
    <div className="min-h-screen bg-background">
      <div className="mx-auto w-full space-y-6 px-6 py-8">
        {/* 헤더 */}
        <div className="flex items-center justify-between rounded-lg border bg-card p-8">
          <div className="flex items-center gap-4">
            <div className="rounded-lg bg-primary/10 p-4">
              <Users className="h-8 w-8 text-primary" />
            </div>
            <div>
              <h1 className="mb-1 text-3xl font-bold text-foreground">대량 메일 발송</h1>
              <p className="text-muted-foreground">CSV 파일로 여러 수신자에게 메일을 발송하세요</p>
            </div>
          </div>
          <Link href="/admin/mail/dashboard">
            <Button variant="outline" size="lg">
              대시보드로
            </Button>
          </Link>
        </div>

        <div className="grid gap-6 lg:grid-cols-2">
          {/* 왼쪽: 설정 */}
          <div className="space-y-6">
            {/* 계정 선택 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">발송 설정</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label htmlFor="account">발송 계정</Label>
                  <Select value={selectedAccountId} onValueChange={setSelectedAccountId}>
                    <SelectTrigger id="account">
                      <SelectValue placeholder="계정 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {accounts.map((account) => (
                        <SelectItem key={account.id} value={account.id}>
                          {account.name} ({account.email})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <Label htmlFor="mode">발송 방식</Label>
                  <Select value={useTemplate ? "template" : "custom"} onValueChange={(v) => setUseTemplate(v === "template")}>
                    <SelectTrigger id="mode">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="template">템플릿 사용</SelectItem>
                      <SelectItem value="custom">직접 작성</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {useTemplate ? (
                  <div>
                    <Label htmlFor="template">템플릿</Label>
                    <Select value={selectedTemplateId} onValueChange={setSelectedTemplateId}>
                      <SelectTrigger id="template">
                        <SelectValue placeholder="템플릿 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {templates.map((template) => (
                          <SelectItem key={template.id} value={template.id}>
                            {template.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                ) : (
                  <div>
                    <Label htmlFor="customHtml">메일 내용</Label>
                    <Textarea
                      id="customHtml"
                      value={customHtml}
                      onChange={(e) => setCustomHtml(e.target.value)}
                      placeholder="메일 내용을 작성하세요..."
                      rows={10}
                      className="text-sm"
                    />
                    {/* <p className="mt-1 text-xs text-muted-foreground">
                      HTML 태그를 사용할 수 있습니다
                    </p> */}
                  </div>
                )}

                <div>
                  <Label htmlFor="subject">제목</Label>
                  <Input
                    id="subject"
                    value={subject}
                    onChange={(e) => setSubject(e.target.value)}
                    placeholder="메일 제목을 입력하세요"
                  />
                </div>
              </CardContent>
            </Card>

            {/* CSV 업로드 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">수신자 업로드</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label htmlFor="csv">CSV 파일</Label>
                  <div className="mt-2 flex gap-2">
                    <Input
                      id="csv"
                      type="file"
                      accept=".csv"
                      onChange={handleFileUpload}
                      disabled={loading}
                    />
                    <Button
                      variant="outline"
                      size="icon"
                      onClick={downloadSampleCsv}
                      title="샘플 다운로드"
                    >
                      <Download className="h-4 w-4" />
                    </Button>
                  </div>
                  <p className="mt-2 text-xs text-muted-foreground">
                    첫 번째 줄은 헤더(email, name, company 등)여야 합니다.
                  </p>
                </div>

                {csvFile && (
                  <div className="flex items-center justify-between rounded-md border bg-muted p-3">
                    <div className="flex items-center gap-2">
                      <FileText className="h-4 w-4 text-muted-foreground" />
                      <span className="text-sm">{csvFile.name}</span>
                    </div>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => {
                        setCsvFile(null);
                        setRecipients([]);
                      }}
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                )}

                {recipients.length > 0 && (
                  <div className="rounded-md border bg-muted p-4">
                    <div className="flex items-center gap-2 text-sm">
                      <CheckCircle2 className="h-4 w-4 text-emerald-600" />
                      <span className="font-medium">{recipients.length}명의 수신자</span>
                    </div>
                    <p className="mt-1 text-xs text-muted-foreground">
                      변수: {Object.keys(recipients[0]?.variables || {}).join(", ")}
                    </p>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>

          {/* 오른쪽: 미리보기 & 발송 */}
          <div className="space-y-6">
            {/* 발송 버튼 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">발송 실행</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                {sending && (
                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-sm">
                      <span>발송 진행 중...</span>
                      <span className="font-medium">
                        {sendProgress.sent} / {sendProgress.total}
                      </span>
                    </div>
                    <div className="h-2 overflow-hidden rounded-full bg-muted">
                      <div
                        className="h-full bg-primary transition-all duration-300"
                        style={{
                          width: `${(sendProgress.sent / sendProgress.total) * 100}%`,
                        }}
                      />
                    </div>
                  </div>
                )}

                <Button
                  onClick={handleSend}
                  disabled={sending || recipients.length === 0}
                  className="w-full"
                  size="lg"
                >
                  {sending ? (
                    <>
                      <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                      발송 중...
                    </>
                  ) : (
                    <>
                      <Send className="mr-2 h-5 w-5" />
                      {recipients.length}명에게 발송
                    </>
                  )}
                </Button>

                <div className="rounded-md border bg-muted p-4">
                  <div className="flex items-start gap-2">
                    <AlertCircle className="mt-0.5 h-4 w-4 text-muted-foreground" />
                    <div className="text-xs text-muted-foreground">
                      <p className="font-medium">주의사항</p>
                      <ul className="mt-1 list-inside list-disc space-y-1">
                        <li>발송 속도는 계정 설정에 따라 제한됩니다</li>
                        <li>대량 발송 시 스팸으로 분류될 수 있습니다</li>
                        <li>발송 후 취소할 수 없습니다</li>
                      </ul>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 수신자 목록 미리보기 */}
            {recipients.length > 0 && (
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">수신자 목록 미리보기</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="max-h-96 space-y-2 overflow-y-auto">
                    {recipients.slice(0, 10).map((recipient, index) => (
                      <div
                        key={index}
                        className="rounded-md border bg-muted p-3 text-sm"
                      >
                        <div className="font-medium">{recipient.email}</div>
                        <div className="mt-1 text-xs text-muted-foreground">
                          {Object.entries(recipient.variables).map(([key, value]) => (
                            <span key={key} className="mr-2">
                              {key}: {value}
                            </span>
                          ))}
                        </div>
                      </div>
                    ))}
                    {recipients.length > 10 && (
                      <p className="text-center text-xs text-muted-foreground">
                        외 {recipients.length - 10}명
                      </p>
                    )}
                  </div>
                </CardContent>
              </Card>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

