import { useState } from "react";
import { useNavigate, useSearchParams } from "react-router";
import { ArrowLeft, Plus, Trash2, Copy, Check, Server } from "lucide-react";
import { ProtectedRoute } from "~/components/protected-route";
import { Header } from "~/components/header";
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card/card";
import { Button } from "~/components/ui/button/button";
import { Input } from "~/components/ui/input/input";
import { Label } from "~/components/ui/label/label";
import { Textarea } from "~/components/ui/textarea/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "~/components/ui/select/select";
import { Badge } from "~/components/ui/badge/badge";
import styles from "./server-config.module.css";
import type { VPNConfig } from "~/data/servers";

export default function ServerConfig() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const serverId = searchParams.get("id");
  const serverName = searchParams.get("name") || "سرور";

  const [configs, setConfigs] = useState<VPNConfig[]>([]);
  const [newConfig, setNewConfig] = useState<Partial<VPNConfig>>({
    protocol: "v2ray",
    config: "",
    remarks: "",
  });
  const [copiedId, setCopiedId] = useState<string | null>(null);

  const handleAddConfig = () => {
    if (!newConfig.config) {
      alert("لطفاً کانفیگ را وارد کنید");
      return;
    }

    const config: VPNConfig = {
      id: Date.now().toString(),
      protocol: (newConfig.protocol || "v2ray") as VPNConfig["protocol"],
      config: newConfig.config,
      port: newConfig.port,
      encryption: newConfig.encryption,
      remarks: newConfig.remarks || `کانفیگ ${configs.length + 1}`,
    };

    setConfigs([...configs, config]);
    setNewConfig({
      protocol: "v2ray",
      config: "",
      remarks: "",
    });
  };

  const handleDeleteConfig = (id: string) => {
    setConfigs(configs.filter((c) => c.id !== id));
  };

  const handleCopyConfig = (config: string, id: string) => {
    navigator.clipboard.writeText(config);
    setCopiedId(id);
    setTimeout(() => setCopiedId(null), 2000);
  };

  const handleSaveConfigs = async () => {
    // TODO: Save to backend
    console.log("Saving configs for server:", serverId, configs);
    alert("کانفیگ‌ها با موفقیت ذخیره شدند");
    navigate("/servers");
  };

  const getProtocolColor = (protocol: string) => {
    switch (protocol) {
      case "v2ray":
        return "var(--color-accent-9)";
      case "openvpn":
        return "var(--color-success-9)";
      case "wireguard":
        return "var(--violet-9)";
      case "ikev2":
        return "var(--cyan-9)";
      case "shadowsocks":
        return "var(--orange-9)";
      default:
        return "var(--color-neutral-9)";
    }
  };

  return (
    <ProtectedRoute>
      <div className={styles.container}>
        <Header />
        <main className={styles.content}>
          <div className={styles.pageHeader}>
            <div>
              <Button variant="outline" onClick={() => navigate("/servers")} className={styles.backButton}>
                <ArrowLeft size={16} />
                بازگشت
              </Button>
              <h1 className={styles.pageTitle}>
                <Server size={24} />
                تنظیمات کانفیگ - {serverName}
              </h1>
              <p className={styles.pageDescription}>اضافه کردن کانفیگ‌های دستی برای اتصال</p>
            </div>
            <Button onClick={handleSaveConfigs} disabled={configs.length === 0}>
              ذخیره تنظیمات
            </Button>
          </div>

          <div className={styles.grid}>
            {/* Add New Config */}
            <Card className={styles.addCard}>
              <CardHeader>
                <CardTitle>افزودن کانفیگ جدید</CardTitle>
              </CardHeader>
              <CardContent className={styles.addForm}>
                <div className={styles.formGroup}>
                  <Label htmlFor="protocol">پروتکل</Label>
                  <Select
                    value={newConfig.protocol}
                    onValueChange={(value) => setNewConfig({ ...newConfig, protocol: value as VPNConfig["protocol"] })}
                  >
                    <SelectTrigger id="protocol">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="v2ray">V2Ray (Vmess/Vless)</SelectItem>
                      <SelectItem value="openvpn">OpenVPN</SelectItem>
                      <SelectItem value="wireguard">WireGuard</SelectItem>
                      <SelectItem value="ikev2">IKEv2</SelectItem>
                      <SelectItem value="shadowsocks">Shadowsocks</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className={styles.formGroup}>
                  <Label htmlFor="config">کانفیگ</Label>
                  <Textarea
                    id="config"
                    placeholder="vmess://eyJhZGQiOiIxOTIuMTY4... یا کانفیگ OpenVPN/WireGuard"
                    value={newConfig.config}
                    onChange={(e) => setNewConfig({ ...newConfig, config: e.target.value })}
                    rows={6}
                    className={styles.configTextarea}
                  />
                  <small className={styles.hint}>
                    برای V2Ray: لینک vmess:// یا vless://
                    <br />
                    برای سایر پروتکل‌ها: محتوای فایل کانفیگ کامل
                  </small>
                </div>

                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <Label htmlFor="port">پورت (اختیاری)</Label>
                    <Input
                      id="port"
                      type="number"
                      placeholder="443"
                      value={newConfig.port || ""}
                      onChange={(e) => setNewConfig({ ...newConfig, port: parseInt(e.target.value) || undefined })}
                    />
                  </div>

                  <div className={styles.formGroup}>
                    <Label htmlFor="encryption">رمزنگاری (اختیاری)</Label>
                    <Input
                      id="encryption"
                      placeholder="aes-256-gcm"
                      value={newConfig.encryption || ""}
                      onChange={(e) => setNewConfig({ ...newConfig, encryption: e.target.value })}
                    />
                  </div>
                </div>

                <div className={styles.formGroup}>
                  <Label htmlFor="remarks">توضیحات</Label>
                  <Input
                    id="remarks"
                    placeholder="کانفیگ اصلی سرور آمریکا"
                    value={newConfig.remarks || ""}
                    onChange={(e) => setNewConfig({ ...newConfig, remarks: e.target.value })}
                  />
                </div>

                <Button onClick={handleAddConfig} className={styles.addButton}>
                  <Plus size={16} />
                  افزودن کانفیگ
                </Button>
              </CardContent>
            </Card>

            {/* Configs List */}
            <Card className={styles.listCard}>
              <CardHeader>
                <CardTitle>
                  کانفیگ‌های ثبت شده <Badge>{configs.length}</Badge>
                </CardTitle>
              </CardHeader>
              <CardContent>
                {configs.length === 0 ? (
                  <div className={styles.emptyState}>
                    <Server size={48} />
                    <p>هنوز کانفیگی اضافه نشده</p>
                  </div>
                ) : (
                  <div className={styles.configsList}>
                    {configs.map((config) => (
                      <div key={config.id} className={styles.configItem}>
                        <div className={styles.configHeader}>
                          <div className={styles.configInfo}>
                            <Badge
                              style={{
                                background: `${getProtocolColor(config.protocol)}20`,
                                color: getProtocolColor(config.protocol),
                                border: `1px solid ${getProtocolColor(config.protocol)}40`,
                              }}
                            >
                              {config.protocol.toUpperCase()}
                            </Badge>
                            <span className={styles.configRemarks}>{config.remarks}</span>
                          </div>
                          <div className={styles.configActions}>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleCopyConfig(config.config, config.id)}
                              className={styles.actionButton}
                            >
                              {copiedId === config.id ? <Check size={14} /> : <Copy size={14} />}
                              {copiedId === config.id ? "کپی شد" : "کپی"}
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleDeleteConfig(config.id)}
                              className={styles.deleteButton}
                            >
                              <Trash2 size={14} />
                            </Button>
                          </div>
                        </div>
                        <div className={styles.configDetails}>
                          {config.port && <span>پورت: {config.port}</span>}
                          {config.encryption && <span>رمزنگاری: {config.encryption}</span>}
                        </div>
                        <div className={styles.configContent}>
                          <code>{config.config.substring(0, 80)}...</code>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </main>
      </div>
    </ProtectedRoute>
  );
}
