"use client";

import React, { useState, useEffect } from "react";
import { Eye, EyeOff, ChevronDown, ChevronRight } from "lucide-react";
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 {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { useToast } from "@/hooks/use-toast";
import {
  ExternalDbConnectionAPI,
  ExternalDbConnection,
  ConnectionTestRequest,
  ConnectionTestResult,
} from "@/lib/api/externalDbConnection";

interface ExternalDbConnectionModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: () => void;
  connection?: ExternalDbConnection;
  supportedDbTypes: Array<{ value: string; label: string }>;
}

// 기본 포트 설정
const DEFAULT_PORTS: Record<string, number> = {
  mysql: 3306,
  postgresql: 5432,
  mariadb: 3306,
  oracle: 1521,
  mssql: 1433,
  sqlite: 0, // SQLite는 파일 기반이므로 포트 없음
};

export const ExternalDbConnectionModal: React.FC<ExternalDbConnectionModalProps> = ({
  isOpen,
  onClose,
  onSave,
  connection,
  supportedDbTypes,
}) => {
  const { toast } = useToast();

  // 상태 관리
  const [loading, setSaving] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [testingConnection, setTestingConnection] = useState(false);
  const [testResult, setTestResult] = useState<ConnectionTestResult | null>(null);

  // 폼 데이터
  const [formData, setFormData] = useState<ExternalDbConnection>({
    connection_name: "",
    description: "",
    db_type: "postgresql",
    host: "localhost",
    port: DEFAULT_PORTS.postgresql,
    database_name: "",
    username: "",
    password: "",
    connection_timeout: 30,
    query_timeout: 60,
    max_connections: 10,
    ssl_enabled: "N",
    ssl_cert_path: "",
    company_code: "*",
    is_active: "Y",
  });

  // 편집 모드인지 확인
  const isEditMode = !!connection;

  // 연결 정보가 변경될 때 폼 데이터 업데이트
  useEffect(() => {
    // 테스트 관련 상태 초기화
    setTestResult(null);

    if (connection) {
      setFormData({
        ...connection,
        // 편집 시에는 비밀번호를 빈 문자열로 설정 (보안상 기존 비밀번호는 보여주지 않음)
        password: "",
      });
    } else {
      // 새 연결 생성 시 기본값 설정
      setFormData({
        connection_name: "",
        description: "",
        db_type: "postgresql",
        host: "localhost",
        port: DEFAULT_PORTS.postgresql,
        database_name: "",
        username: "",
        password: "",
        connection_timeout: 30,
        query_timeout: 60,
        max_connections: 10,
        ssl_enabled: "N",
        ssl_cert_path: "",
        company_code: "*",
        is_active: "Y",
      });
    }
  }, [connection]);

  // DB 타입 변경 시 기본 포트 설정
  const handleDbTypeChange = (dbType: string) => {
    setFormData({
      ...formData,
      db_type: dbType as ExternalDbConnection["db_type"],
      port: DEFAULT_PORTS[dbType] || 5432,
    });
  };

  // 입력값 변경 처리
  const handleInputChange = (field: keyof ExternalDbConnection, value: string | number) => {
    setFormData({
      ...formData,
      [field]: value,
    });
  };

  // 폼 검증
  const validateForm = (): boolean => {
    if (!formData.connection_name.trim()) {
      toast({
        title: "검증 오류",
        description: "연결명을 입력해주세요.",
        variant: "destructive",
      });
      return false;
    }

    if (!formData.host.trim()) {
      toast({
        title: "검증 오류",
        description: "호스트를 입력해주세요.",
        variant: "destructive",
      });
      return false;
    }

    if (!formData.database_name.trim()) {
      toast({
        title: "검증 오류",
        description: "데이터베이스명을 입력해주세요.",
        variant: "destructive",
      });
      return false;
    }

    if (!formData.username.trim()) {
      toast({
        title: "검증 오류",
        description: "사용자명을 입력해주세요.",
        variant: "destructive",
      });
      return false;
    }

    if (!isEditMode && !formData.password.trim()) {
      toast({
        title: "검증 오류",
        description: "비밀번호를 입력해주세요.",
        variant: "destructive",
      });
      return false;
    }

    return true;
  };

  // 연결 테스트 처리
  const handleTestConnection = async () => {
    // 기본 필수 필드 검증
    if (!formData.host.trim()) {
      toast({
        title: "검증 오류",
        description: "호스트를 입력해주세요.",
        variant: "destructive",
      });
      return;
    }

    if (!formData.database_name.trim()) {
      toast({
        title: "검증 오류",
        description: "데이터베이스명을 입력해주세요.",
        variant: "destructive",
      });
      return;
    }

    if (!formData.username.trim()) {
      toast({
        title: "검증 오류",
        description: "사용자명을 입력해주세요.",
        variant: "destructive",
      });
      return;
    }

    if (!formData.password.trim()) {
      toast({
        title: "검증 오류",
        description: "비밀번호를 입력해주세요.",
        variant: "destructive",
      });
      return;
    }

    try {
      setTestingConnection(true);
      setTestResult(null);

      // 편집 모드일 때만 연결 테스트 실행
      if (!isEditMode || !connection?.id) {
        toast({
          title: "연결 테스트 불가",
          description: "연결을 먼저 저장한 후 테스트할 수 있습니다.",
          variant: "destructive",
        });
        return;
      }

      const result = await ExternalDbConnectionAPI.testConnection(connection.id, formData.password);
      setTestResult(result);

      if (result.success) {
        toast({
          title: "연결 테스트 성공",
          description: result.message,
        });
      } else {
        toast({
          title: "연결 테스트 실패",
          description: result.message,
          variant: "destructive",
        });
      }
    } catch (error) {
      console.error("연결 테스트 오류:", error);
      const errorResult: ConnectionTestResult = {
        success: false,
        message: "연결 테스트 중 오류가 발생했습니다.",
        error: {
          code: "TEST_ERROR",
          details: error instanceof Error ? error.message : "알 수 없는 오류",
        },
      };
      setTestResult(errorResult);

      toast({
        title: "연결 테스트 오류",
        description: errorResult.message,
        variant: "destructive",
      });
    } finally {
      setTestingConnection(false);
    }
  };

  // 저장 처리
  const handleSave = async () => {
    if (!validateForm()) return;

    try {
      setSaving(true);

      // 편집 모드에서 비밀번호가 비어있으면 기존 비밀번호 유지
      let dataToSave = { ...formData };
      if (isEditMode && !dataToSave.password.trim()) {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const { password, ...dataWithoutPassword } = dataToSave;
        dataToSave = dataWithoutPassword as ExternalDbConnection;
      }

      if (isEditMode && connection?.id) {
        await ExternalDbConnectionAPI.updateConnection(connection.id, dataToSave);
        toast({
          title: "성공",
          description: "연결 정보가 수정되었습니다.",
        });
      } else {
        await ExternalDbConnectionAPI.createConnection(dataToSave);
        toast({
          title: "성공",
          description: "새 연결이 생성되었습니다.",
        });
      }

      onSave();
    } catch (error) {
      console.error("연결 저장 오류:", error);
      toast({
        title: "오류",
        description: error instanceof Error ? error.message : "연결 저장에 실패했습니다.",
        variant: "destructive",
      });
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-h-[90vh] max-w-[95vw] overflow-hidden sm:max-w-2xl">
        <DialogHeader>
          <DialogTitle className="text-base sm:text-lg">
            {isEditMode ? "연결 정보 수정" : "새 외부 DB 연결 추가"}
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-3 sm:space-y-4">
          {/* 기본 정보 */}
          <div className="space-y-3 sm:space-y-4">
            <h3 className="text-sm font-semibold sm:text-base">기본 정보</h3>

            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4">
              <div>
                <Label htmlFor="connection_name" className="text-xs sm:text-sm">
                  연결명 <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="connection_name"
                  value={formData.connection_name}
                  onChange={(e) => handleInputChange("connection_name", e.target.value)}
                  placeholder="예: 운영 DB"
                  className="h-8 text-xs sm:h-10 sm:text-sm"
                />
              </div>

              <div>
                <Label htmlFor="db_type" className="text-xs sm:text-sm">
                  DB 타입 <span className="text-destructive">*</span>
                </Label>
                <Select value={formData.db_type} onValueChange={handleDbTypeChange}>
                  <SelectTrigger className="h-8 text-xs sm:h-10 sm:text-sm">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {supportedDbTypes.map((type) => (
                      <SelectItem key={type.value} value={type.value}>
                        {type.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <Label htmlFor="description" className="text-xs sm:text-sm">
                설명
              </Label>
              <Textarea
                id="description"
                value={formData.description || ""}
                onChange={(e) => handleInputChange("description", e.target.value)}
                placeholder="연결에 대한 설명을 입력하세요"
                rows={2}
                className="text-xs sm:text-sm"
              />
            </div>
          </div>

          {/* 연결 정보 */}
          <div className="space-y-3 sm:space-y-4">
            <h3 className="text-sm font-semibold sm:text-base">연결 정보</h3>

            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4">
              <div>
                <Label htmlFor="host" className="text-xs sm:text-sm">
                  호스트 <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="host"
                  value={formData.host}
                  onChange={(e) => handleInputChange("host", e.target.value)}
                  placeholder="localhost"
                  className="h-8 text-xs sm:h-10 sm:text-sm"
                />
              </div>

              <div>
                <Label htmlFor="port" className="text-xs sm:text-sm">
                  포트 <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="port"
                  type="number"
                  value={formData.port}
                  onChange={(e) => handleInputChange("port", parseInt(e.target.value) || 0)}
                  placeholder="5432"
                  className="h-8 text-xs sm:h-10 sm:text-sm"
                />
              </div>
            </div>

            <div>
              <Label htmlFor="database_name" className="text-xs sm:text-sm">
                데이터베이스명 <span className="text-destructive">*</span>
              </Label>
              <Input
                id="database_name"
                value={formData.database_name}
                onChange={(e) => handleInputChange("database_name", e.target.value)}
                placeholder="database_name"
                className="h-8 text-xs sm:h-10 sm:text-sm"
              />
            </div>

            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4">
              <div>
                <Label htmlFor="username" className="text-xs sm:text-sm">
                  사용자명 <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="username"
                  value={formData.username}
                  onChange={(e) => handleInputChange("username", e.target.value)}
                  placeholder="username"
                  className="h-8 text-xs sm:h-10 sm:text-sm"
                />
              </div>

              <div>
                <Label htmlFor="password" className="text-xs sm:text-sm">
                  비밀번호 {isEditMode ? "(변경 시에만 입력)" : <span className="text-destructive">*</span>}
                </Label>
                <div className="relative">
                  <Input
                    id="password"
                    type={showPassword ? "text" : "password"}
                    value={formData.password}
                    onChange={(e) => handleInputChange("password", e.target.value)}
                    placeholder={isEditMode ? "변경하지 않으려면 비워두세요" : "password"}
                    className="h-8 text-xs sm:h-10 sm:text-sm"
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="absolute top-0 right-0 h-full px-3 py-2 hover:bg-transparent"
                    onClick={() => setShowPassword(!showPassword)}
                  >
                    {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </Button>
                </div>
              </div>
            </div>

            {/* 연결 테스트 */}
            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <Button
                  type="button"
                  variant="outline"
                  onClick={handleTestConnection}
                  disabled={
                    testingConnection ||
                    !formData.host ||
                    !formData.database_name ||
                    !formData.username ||
                    !formData.password
                  }
                  className="w-32"
                >
                  {testingConnection ? "테스트 중..." : "연결 테스트"}
                </Button>
                {testingConnection && <div className="text-muted-foreground text-sm">연결을 확인하고 있습니다...</div>}
              </div>

              {/* 테스트 결과 표시 */}
              {testResult && (
                <div
                  className={`rounded-md border p-3 text-sm ${
                    testResult.success
                      ? "border-emerald-200 bg-emerald-50 text-emerald-800"
                      : "border-destructive/20 bg-destructive/10 text-red-800"
                  }`}
                >
                  <div className="font-medium">{testResult.success ? "✅ 연결 성공" : "❌ 연결 실패"}</div>
                  <div className="mt-1">{testResult.message}</div>

                  {testResult.success && testResult.details && (
                    <div className="mt-2 space-y-1 text-xs">
                      {testResult.details.response_time && <div>응답 시간: {testResult.details.response_time}ms</div>}
                      {testResult.details.server_version && <div>서버 버전: {testResult.details.server_version}</div>}
                      {testResult.details.database_size && (
                        <div>데이터베이스 크기: {testResult.details.database_size}</div>
                      )}
                    </div>
                  )}

                  {!testResult.success && testResult.error && (
                    <div className="mt-2 text-xs">
                      <div>오류 코드: {testResult.error.code}</div>
                      {testResult.error.details && (
                        <div className="text-destructive mt-1">{testResult.error.details}</div>
                      )}
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>

          {/* 고급 설정 */}
          <div className="space-y-4">
            <Button
              type="button"
              variant="ghost"
              onClick={() => setShowAdvanced(!showAdvanced)}
              className="flex h-auto items-center gap-2 p-0 font-medium"
            >
              {showAdvanced ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
              고급 설정
            </Button>

            {showAdvanced && (
              <div className="space-y-4 border-l-2 border-border pl-6">
                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <Label htmlFor="connection_timeout">연결 타임아웃 (초)</Label>
                    <Input
                      id="connection_timeout"
                      type="number"
                      value={formData.connection_timeout || 30}
                      onChange={(e) => handleInputChange("connection_timeout", parseInt(e.target.value) || 30)}
                    />
                  </div>

                  <div>
                    <Label htmlFor="query_timeout">쿼리 타임아웃 (초)</Label>
                    <Input
                      id="query_timeout"
                      type="number"
                      value={formData.query_timeout || 60}
                      onChange={(e) => handleInputChange("query_timeout", parseInt(e.target.value) || 60)}
                    />
                  </div>

                  <div>
                    <Label htmlFor="max_connections">최대 연결 수</Label>
                    <Input
                      id="max_connections"
                      type="number"
                      value={formData.max_connections || 10}
                      onChange={(e) => handleInputChange("max_connections", parseInt(e.target.value) || 10)}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="ssl_enabled">SSL 사용</Label>
                    <Select
                      value={formData.ssl_enabled || "N"}
                      onValueChange={(value) => handleInputChange("ssl_enabled", value)}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Y">사용</SelectItem>
                        <SelectItem value="N">사용 안함</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label htmlFor="is_active">활성 상태</Label>
                    <Select value={formData.is_active} onValueChange={(value) => handleInputChange("is_active", value)}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Y">활성</SelectItem>
                        <SelectItem value="N">비활성</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                {formData.ssl_enabled === "Y" && (
                  <div>
                    <Label htmlFor="ssl_cert_path">SSL 인증서 경로</Label>
                    <Input
                      id="ssl_cert_path"
                      value={formData.ssl_cert_path || ""}
                      onChange={(e) => handleInputChange("ssl_cert_path", e.target.value)}
                      placeholder="/path/to/ssl/cert.pem"
                    />
                  </div>
                )}
              </div>
            )}
          </div>
        </div>

        <DialogFooter className="gap-2 sm:gap-0">
          <Button
            variant="outline"
            onClick={onClose}
            disabled={loading}
            className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
          >
            취소
          </Button>
          <Button
            onClick={handleSave}
            disabled={loading}
            className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
          >
            {loading ? "저장 중..." : isEditMode ? "수정" : "생성"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
