"use client";

import { useEffect, useState, useCallback } from "react";
import { getDLPPolicies, createDLPolicy, DLPPolicy } from "@/lib/api";
import { ShieldAlert, RefreshCw, Plus, X, Check } from "lucide-react";

const COMMON_PATTERNS = [
  { label: "Credit Card Numbers", value: "credit_card" },
  { label: "SSN / Social Security", value: "ssn" },
  { label: "Email Addresses", value: "email" },
  { label: "API Keys / Tokens", value: "api_key" },
  { label: "Phone Numbers", value: "phone" },
  { label: "IP Addresses", value: "ip_address" },
];

const ACTIONS: { value: "block" | "alert" | "redact"; label: string }[] = [
  { value: "block", label: "Block" },
  { value: "alert", label: "Alert" },
  { value: "redact", label: "Redact" },
];

export function DLPPolicies() {
  const [policies, setPolicies] = useState<DLPPolicy[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [showCreate, setShowCreate] = useState(false);

  // Create form
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [selectedPatterns, setSelectedPatterns] = useState<string[]>([]);
  const [action, setAction] = useState<"block" | "alert" | "redact">("alert");

  const loadPolicies = useCallback(() => {
    setLoading(true);
    setError("");
    getDLPPolicies()
      .then((data) => setPolicies(Array.isArray(data) ? data : []))
      .catch((err) => {
        console.error("Failed to load DLP policies:", err);
        setError("Failed to load DLP policies");
      })
      .finally(() => setLoading(false));
  }, []);

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

  const togglePattern = (pattern: string) => {
    setSelectedPatterns((prev) =>
      prev.includes(pattern)
        ? prev.filter((p) => p !== pattern)
        : [...prev, pattern]
    );
  };

  const handleCreate = () => {
    if (!name.trim() || selectedPatterns.length === 0) return;
    createDLPolicy({
      name: name.trim(),
      description: description.trim() || undefined,
      patterns: selectedPatterns,
      action,
    })
      .then((newPolicy) => {
        setPolicies((prev) => [...prev, newPolicy]);
        setName("");
        setDescription("");
        setSelectedPatterns([]);
        setAction("alert");
        setShowCreate(false);
      })
      .catch((err) => {
        console.error("Failed to create DLP policy:", err);
        setError("Failed to create DLP policy");
      });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center text-gray-400 py-12">
        <RefreshCw size={20} className="animate-pulse" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center text-slack-red py-12 text-sm">
        {error}
        <button onClick={loadPolicies} className="ml-2 text-slack-purple hover:underline">
          Retry
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-sm font-semibold text-gray-800 flex items-center gap-2">
            <ShieldAlert size={18} className="text-slack-purple" />
            Data Loss Prevention
          </h3>
          <p className="text-xs text-gray-400 mt-0.5">
            Prevent sensitive data from being shared in messages
          </p>
        </div>
        <button
          onClick={() => setShowCreate(!showCreate)}
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-slack-purple text-white text-sm font-medium hover:bg-slack-darkpurple transition-colors"
        >
          {showCreate ? <X size={16} /> : <Plus size={16} />}
          {showCreate ? "Cancel" : "New Policy"}
        </button>
      </div>

      {/* Create form */}
      {showCreate && (
        <div className="p-4 rounded-lg border border-gray-200 bg-gray-50 space-y-3">
          <div>
            <label className="text-xs font-medium text-gray-500 mb-1 block">Policy Name</label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="e.g. Block credit cards in #general"
              className="w-full px-3 py-2 rounded-md border border-gray-300 text-sm focus:outline-none focus:ring-2 focus:ring-slack-purple"
            />
          </div>
          <div>
            <label className="text-xs font-medium text-gray-500 mb-1 block">Description</label>
            <input
              type="text"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Describe the policy"
              className="w-full px-3 py-2 rounded-md border border-gray-300 text-sm focus:outline-none focus:ring-2 focus:ring-slack-purple"
            />
          </div>
          <div>
            <label className="text-xs font-medium text-gray-500 mb-1 block">Detection Patterns</label>
            <div className="flex flex-wrap gap-2">
              {COMMON_PATTERNS.map((p) => (
                <button
                  key={p.value}
                  onClick={() => togglePattern(p.value)}
                  className={`flex items-center gap-1 px-3 py-1.5 rounded-full text-xs font-medium transition-colors ${
                    selectedPatterns.includes(p.value)
                      ? "bg-slack-purple text-white"
                      : "bg-white text-gray-600 border border-gray-300 hover:bg-gray-100"
                  }`}
                >
                  {selectedPatterns.includes(p.value) && <Check size={10} />}
                  {p.label}
                </button>
              ))}
            </div>
          </div>
          <div>
            <label className="text-xs font-medium text-gray-500 mb-1 block">Action</label>
            <div className="flex gap-2">
              {ACTIONS.map((a) => (
                <button
                  key={a.value}
                  onClick={() => setAction(a.value)}
                  className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
                    action === a.value
                      ? "bg-slack-purple text-white"
                      : "bg-white text-gray-600 border border-gray-300"
                  }`}
                >
                  {a.label}
                </button>
              ))}
            </div>
          </div>
          <button
            onClick={handleCreate}
            disabled={!name.trim() || selectedPatterns.length === 0}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-slack-purple text-white text-sm font-medium hover:bg-slack-darkpurple transition-colors disabled:opacity-50"
          >
            <ShieldAlert size={14} />
            Create DLP Policy
          </button>
        </div>
      )}

      {/* Policies list */}
      {policies.length === 0 && !showCreate ? (
        <div className="flex flex-col items-center justify-center py-12 text-gray-400">
          <ShieldAlert size={40} className="mb-3 opacity-50" />
          <p className="text-sm">No DLP policies configured.</p>
          <p className="text-xs mt-1">Create a policy to prevent data leaks.</p>
        </div>
      ) : (
        <div className="space-y-2">
          {policies.map((policy) => (
            <div
              key={policy.id}
              className="p-3 rounded-lg border border-gray-200 bg-white shadow-sm"
            >
              <div className="flex items-start justify-between gap-3">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <h4 className="text-sm font-semibold text-gray-800">{policy.name}</h4>
                    <span
                      className={`text-[10px] px-2 py-0.5 rounded-full font-medium ${
                        policy.enabled
                          ? "bg-slack-green/10 text-slack-green"
                          : "bg-gray-100 text-gray-400"
                      }`}
                    >
                      {policy.enabled ? "Active" : "Disabled"}
                    </span>
                    <span className="text-[10px] px-2 py-0.5 rounded-full bg-slack-red/10 text-slack-red font-medium capitalize">
                      {policy.action}
                    </span>
                  </div>
                  {policy.description && (
                    <p className="text-xs text-gray-500 mt-1">{policy.description}</p>
                  )}
                  <div className="flex flex-wrap gap-1 mt-2">
                    {policy.patterns.map((pattern) => (
                      <span
                        key={pattern}
                        className="inline-block text-[10px] px-2 py-0.5 rounded bg-gray-100 text-gray-500"
                      >
                        {pattern}
                      </span>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export default DLPPolicies;