"use client";

import { useEffect, useState, useCallback } from "react";
import {
  getRetentionPolicies,
  createRetentionPolicy,
  updateRetentionPolicy,
  deleteRetentionPolicy,
  RetentionPolicy,
} from "@/lib/api";
import { Trash2, RefreshCw, Clock, Plus, X, ShieldCheck } from "lucide-react";

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

  // New policy form state
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [scope, setScope] = useState<"messages" | "files" | "all">("messages");
  const [durationDays, setDurationDays] = useState(30);
  const [action, setAction] = useState<"delete" | "archive">("delete");

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

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

  const handleCreate = () => {
    if (!name.trim()) return;
    createRetentionPolicy({
      name: name.trim(),
      description: description.trim() || undefined,
      scope,
      duration_days: durationDays,
      action,
    })
      .then((newPolicy) => {
        setPolicies((prev) => [...prev, newPolicy]);
        setName("");
        setDescription("");
        setScope("messages");
        setDurationDays(30);
        setAction("delete");
        setShowCreate(false);
      })
      .catch((err) => {
        console.error("Failed to create retention policy:", err);
        setError("Failed to create retention policy");
      });
  };

  const handleToggle = (policy: RetentionPolicy) => {
    updateRetentionPolicy(policy.id, { enabled: !policy.enabled })
      .then((updated) => {
        setPolicies((prev) => prev.map((p) => (p.id === policy.id ? updated : p)));
      })
      .catch((err) => console.error("Failed to toggle policy:", err));
  };

  const handleDelete = (policy: RetentionPolicy) => {
    if (!confirm(`Delete retention policy "${policy.name}"?`)) return;
    deleteRetentionPolicy(policy.id)
      .then(() => {
        setPolicies((prev) => prev.filter((p) => p.id !== policy.id));
      })
      .catch((err) => console.error("Failed to delete policy:", err));
  };

  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>
          <h2 className="text-lg font-bold text-gray-800 flex items-center gap-2">
            <Clock size={20} className="text-slack-purple" />
            Data Retention Policies
          </h2>
          <p className="text-sm text-gray-400 mt-0.5">
            Configure how long messages and files are retained
          </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. Delete messages after 30 days"
              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 (optional)</label>
            <input
              type="text"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Describe the policy purpose"
              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 className="grid grid-cols-3 gap-3">
            <div>
              <label className="text-xs font-medium text-gray-500 mb-1 block">Scope</label>
              <select
                value={scope}
                onChange={(e) => setScope(e.target.value as "messages" | "files" | "all")}
                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 bg-white"
              >
                <option value="messages">Messages</option>
                <option value="files">Files</option>
                <option value="all">All</option>
              </select>
            </div>
            <div>
              <label className="text-xs font-medium text-gray-500 mb-1 block">Retention (days)</label>
              <input
                type="number"
                min={1}
                value={durationDays}
                onChange={(e) => setDurationDays(parseInt(e.target.value) || 30)}
                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">Action</label>
              <select
                value={action}
                onChange={(e) => setAction(e.target.value as "delete" | "archive")}
                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 bg-white"
              >
                <option value="delete">Delete</option>
                <option value="archive">Archive</option>
              </select>
            </div>
          </div>
          <button
            onClick={handleCreate}
            disabled={!name.trim()}
            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"
          >
            <ShieldCheck size={14} />
            Create Policy
          </button>
        </div>
      )}

      {/* Policies list */}
      {policies.length === 0 && !showCreate ? (
        <div className="flex flex-col items-center justify-center py-16 text-gray-400">
          <Clock size={48} className="mb-3 opacity-50" />
          <p className="text-sm">No retention policies configured.</p>
          <p className="text-xs mt-1">Create a policy to control data retention.</p>
        </div>
      ) : (
        <div className="space-y-3">
          {policies.map((policy) => (
            <div
              key={policy.id}
              className="p-4 rounded-lg border border-gray-200 bg-white shadow-sm hover:border-slack-purple/30 transition-colors"
            >
              <div className="flex items-start justify-between gap-3">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <h3 className="font-semibold text-gray-800">{policy.name}</h3>
                    <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-gray-100 text-gray-500 capitalize">
                      {policy.scope}
                    </span>
                  </div>
                  {policy.description && (
                    <p className="text-sm text-gray-500 mt-1">{policy.description}</p>
                  )}
                  <div className="flex items-center gap-3 mt-2 text-xs text-gray-400">
                    <span>Retain for {policy.duration_days} days</span>
                    <span className="capitalize">Action: {policy.action}</span>
                  </div>
                </div>
                <div className="flex items-center gap-1 flex-shrink-0">
                  <button
                    onClick={() => handleToggle(policy)}
                    className="px-2 py-1 text-xs text-gray-500 hover:text-slack-purple hover:bg-gray-50 rounded transition-colors"
                  >
                    {policy.enabled ? "Disable" : "Enable"}
                  </button>
                  <button
                    onClick={() => handleDelete(policy)}
                    className="p-1.5 rounded text-gray-400 hover:text-slack-red hover:bg-gray-50 transition-colors"
                    title="Delete policy"
                  >
                    <Trash2 size={14} />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export default RetentionPolicies;