"use client";

import { useState, useEffect } from 'react';
import {
    CheckCircleIcon,
    ExclamationTriangleIcon,
    PlusIcon,
    ShieldCheckIcon,
    ClockIcon,
    PencilIcon,
    TrashIcon
} from '@heroicons/react/24/outline';
import api from '../../lib/api';

interface Policy {
    id: number;
    name: string;
    description: string;
    status: string;
    compliance: number;
    category: string;
    critical_sla_days: number;
    high_sla_days: number;
    medium_sla_days: number;
    low_sla_days: number;
}

const DEFAULT_POLICY: Partial<Policy> = {
    name: '',
    description: '',
    category: 'Vulnerability Management',
    status: 'active',
    critical_sla_days: 2,
    high_sla_days: 7,
    medium_sla_days: 30,
    low_sla_days: 90
};

export default function PoliciesPage() {
    const [policies, setPolicies] = useState<Policy[]>([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingPolicy, setEditingPolicy] = useState<Partial<Policy>>(DEFAULT_POLICY);
    const [isEditing, setIsEditing] = useState(false);

    const fetchPolicies = async () => {
        try {
            const response = await api.get('/api/v1/policies');
            setPolicies(response.data.map((p: any) => ({
                ...p,
                compliance: p.compliance || 100
            })));
        } catch (error) {
            console.error("Failed to fetch policies", error);
        } finally {
            setLoading(false);
        }
    };

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

    const handleCreate = () => {
        setEditingPolicy({ ...DEFAULT_POLICY });
        setIsEditing(false);
        setIsModalOpen(true);
    };

    const handleEdit = (policy: Policy) => {
        setEditingPolicy({ ...policy });
        setIsEditing(true);
        setIsModalOpen(true);
    };

    const handleSave = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
            if (isEditing && editingPolicy.id) {
                await api.put(`/api/v1/policies/${editingPolicy.id}`, editingPolicy);
            } else {
                await api.post('/api/v1/policies', editingPolicy);
            }
            fetchPolicies();
            setIsModalOpen(false);
        } catch (error) {
            console.error("Failed to save policy", error);
            alert("Failed to save policy");
        }
    };

    const handleDelete = async (id: number) => {
        if (!confirm("Are you sure you want to delete this policy? Assets assigned to it will fallback to defaults.")) return;
        try {
            await api.delete(`/api/v1/policies/${id}`);
            fetchPolicies();
        } catch (error) {
            console.error("Failed to delete policy", error);
        }
    };

    return (
        <div className="space-y-8">
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-2xl font-bold text-gray-900 font-mono">Security Policies</h1>
                    <p className="text-sm text-gray-500 mt-1">Define remediation SLAs and compliance standards for your infrastructure.</p>
                </div>
                <button
                    onClick={handleCreate}
                    className="flex items-center gap-2 px-4 py-2 bg-vulncheck-blue text-white rounded-lg font-bold hover:bg-blue-700 transition-colors shadow-lg shadow-blue-500/20"
                >
                    <PlusIcon className="h-5 w-5" />
                    Create Policy
                </button>
            </div>

            <div className="grid grid-cols-1 gap-6 sm:grid-cols-3">
                <div className="bg-white rounded-xl border border-gray-100 p-6 shadow-sm">
                    <dt className="text-xs font-bold text-gray-500 uppercase tracking-widest">Global Compliance</dt>
                    <dd className="mt-2 text-3xl font-extrabold text-gray-900">
                        {policies.length > 0
                            ? (policies.reduce((sum, p) => sum + (p.compliance || 0), 0) / policies.length).toFixed(1)
                            : 0}%
                    </dd>
                    <div className="mt-4 w-full bg-gray-100 h-2 rounded-full overflow-hidden">
                        <div
                            className="bg-vulncheck-blue h-full transition-all duration-500"
                            style={{ width: `${policies.length > 0 ? (policies.reduce((sum, p) => sum + (p.compliance || 0), 0) / policies.length) : 0}%` }}
                        ></div>
                    </div>
                </div>
                <div className="bg-white rounded-xl border border-gray-100 p-6 shadow-sm">
                    <dt className="text-xs font-bold text-gray-500 uppercase tracking-widest">Active Frameworks</dt>
                    <dd className="mt-2 text-3xl font-extrabold text-gray-900">{policies.filter(p => p.status === 'active').length}</dd>
                    <p className="mt-2 text-xs text-green-600 font-bold flex items-center gap-1">
                        <CheckCircleIcon className="h-4 w-4" /> All responding
                    </p>
                </div>

            </div>

            <div className="grid grid-cols-1 gap-6">
                {policies.map((policy) => (
                    <div key={policy.id} className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden hover:border-vulncheck-blue/30 transition-all group">
                        <div className="p-6 flex flex-col md:flex-row md:items-center justify-between gap-6">
                            <div className="flex items-start gap-4">
                                <div className={`p-3 rounded-xl ${policy.status === 'active' ? 'bg-green-50 text-green-600' : 'bg-gray-50 text-gray-400'}`}>
                                    <ShieldCheckIcon className="h-8 w-8" />
                                </div>
                                <div>
                                    <div className="flex items-center gap-3">
                                        <h3 className="text-lg font-bold text-gray-900">{policy.name}</h3>
                                        <span className={`px-2 py-0.5 rounded text-[10px] font-bold uppercase ${policy.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'
                                            }`}>
                                            {policy.status}
                                        </span>
                                    </div>
                                    <p className="text-sm text-gray-500 mt-1">{policy.description}</p>
                                    <div className="mt-4 flex flex-wrap gap-4">
                                        <div className="flex items-center gap-1.5 text-xs font-mono bg-gray-50 px-2 py-1 rounded">
                                            <span className="w-2 h-2 rounded-full bg-red-500"></span>
                                            <span className="text-gray-500">Critical:</span>
                                            <span className="text-gray-900 font-bold">{policy.critical_sla_days}d</span>
                                        </div>
                                        <div className="flex items-center gap-1.5 text-xs font-mono bg-gray-50 px-2 py-1 rounded">
                                            <span className="w-2 h-2 rounded-full bg-orange-500"></span>
                                            <span className="text-gray-500">High:</span>
                                            <span className="text-gray-900 font-bold">{policy.high_sla_days}d</span>
                                        </div>
                                        <div className="flex items-center gap-1.5 text-xs font-mono bg-gray-50 px-2 py-1 rounded">
                                            <span className="w-2 h-2 rounded-full bg-blue-500"></span>
                                            <span className="text-gray-500">Medium:</span>
                                            <span className="text-gray-900 font-bold">{policy.medium_sla_days}d</span>
                                        </div>
                                        <div className="flex items-center gap-1.5 text-xs font-mono bg-gray-50 px-2 py-1 rounded">
                                            <span className="w-2 h-2 rounded-full bg-green-500"></span>
                                            <span className="text-gray-500">Low:</span>
                                            <span className="text-gray-900 font-bold">{policy.low_sla_days}d</span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div className="flex items-center gap-6 border-t md:border-t-0 pt-6 md:pt-0 border-gray-50">
                                <div className="text-right">
                                    <div className="text-2xl font-black text-gray-900">{policy.compliance}%</div>
                                    <div className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">Compliance</div>
                                </div>
                                <div className="flex gap-2">
                                    <button
                                        onClick={() => handleEdit(policy)}
                                        className="p-2 text-gray-400 hover:text-vulncheck-blue hover:bg-blue-50 rounded-lg transition-all"
                                        title="Edit Policy"
                                    >
                                        <PencilIcon className="h-5 w-5" />
                                    </button>
                                    <button
                                        onClick={() => handleDelete(policy.id)}
                                        className="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-all"
                                        title="Delete Policy"
                                    >
                                        <TrashIcon className="h-5 w-5" />
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                ))}
            </div>

            {/* Edit/Create Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-900/60 backdrop-blur-sm px-4">
                    <div className="bg-white rounded-2xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto border border-gray-100">
                        <div className="p-8">
                            <h3 className="text-2xl font-bold text-gray-900 mb-2">{isEditing ? 'Edit Policy' : 'Create Security Policy'}</h3>
                            <p className="text-sm text-gray-500 mb-8">Set detection thresholds and mandatory remediation windows.</p>

                            <form onSubmit={handleSave} className="space-y-6">
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div className="md:col-span-2">
                                        <label className="block text-xs font-bold text-gray-400 uppercase tracking-widest mb-2">Policy Name</label>
                                        <input
                                            type="text"
                                            required
                                            value={editingPolicy.name}
                                            onChange={(e) => setEditingPolicy({ ...editingPolicy, name: e.target.value })}
                                            className="w-full bg-gray-50 border-gray-100 rounded-xl px-4 py-3 focus:ring-vulncheck-blue focus:border-vulncheck-blue"
                                            placeholder="e.g. Critical Infrastructure SLA"
                                        />
                                    </div>
                                    <div className="md:col-span-2">
                                        <label className="block text-xs font-bold text-gray-400 uppercase tracking-widest mb-2">Description</label>
                                        <textarea
                                            rows={2}
                                            value={editingPolicy.description}
                                            onChange={(e) => setEditingPolicy({ ...editingPolicy, description: e.target.value })}
                                            className="w-full bg-gray-50 border-gray-100 rounded-xl px-4 py-3 focus:ring-vulncheck-blue focus:border-vulncheck-blue"
                                            placeholder="Remediation standards for high-security systems..."
                                        />
                                    </div>

                                    <div>
                                        <label className="block text-xs font-bold text-gray-400 uppercase tracking-widest mb-2">Category</label>
                                        <input
                                            type="text"
                                            value={editingPolicy.category}
                                            onChange={(e) => setEditingPolicy({ ...editingPolicy, category: e.target.value })}
                                            className="w-full bg-gray-50 border-gray-100 rounded-xl px-4 py-3 focus:ring-vulncheck-blue focus:border-vulncheck-blue"
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-xs font-bold text-gray-400 uppercase tracking-widest mb-2">Operational Status</label>
                                        <select
                                            value={editingPolicy.status}
                                            onChange={(e) => setEditingPolicy({ ...editingPolicy, status: e.target.value })}
                                            className="w-full bg-gray-50 border-gray-100 rounded-xl px-4 py-3 focus:ring-vulncheck-blue focus:border-vulncheck-blue"
                                        >
                                            <option value="active">Active Enforcement</option>
                                            <option value="warning">Observation Only</option>
                                            <option value="disabled">Disabled</option>
                                        </select>
                                        <p className="mt-2 text-[10px] text-gray-500 font-mono">
                                            {editingPolicy.status === "active" ? "Triggers alerts on SLA breach." :
                                                editingPolicy.status === "warning" ? "Logs breaches without alerting." :
                                                    "Policy is inactive."}
                                        </p>
                                    </div>

                                    {/* SLA Section */}
                                    <div className="md:col-span-2 mt-4">
                                        <h4 className="text-xs font-bold text-gray-900 border-b border-gray-50 pb-2 mb-4 uppercase tracking-widest">Remediation SLAs (Days)</h4>
                                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                            <div>
                                                <label className="block text-[10px] font-bold text-red-500 mb-1 uppercase">Critical</label>
                                                <input
                                                    type="number"
                                                    value={editingPolicy.critical_sla_days}
                                                    onChange={(e) => setEditingPolicy({ ...editingPolicy, critical_sla_days: parseInt(e.target.value) })}
                                                    className="w-full bg-red-50/30 border-red-100 rounded-lg px-3 py-2 text-sm font-bold focus:ring-red-500 focus:border-red-500"
                                                />
                                            </div>
                                            <div>
                                                <label className="block text-[10px] font-bold text-orange-500 mb-1 uppercase">High</label>
                                                <input
                                                    type="number"
                                                    value={editingPolicy.high_sla_days}
                                                    onChange={(e) => setEditingPolicy({ ...editingPolicy, high_sla_days: parseInt(e.target.value) })}
                                                    className="w-full bg-orange-50/30 border-orange-100 rounded-lg px-3 py-2 text-sm font-bold focus:ring-orange-500 focus:border-orange-500"
                                                />
                                            </div>
                                            <div>
                                                <label className="block text-[10px] font-bold text-blue-500 mb-1 uppercase">Medium</label>
                                                <input
                                                    type="number"
                                                    value={editingPolicy.medium_sla_days}
                                                    onChange={(e) => setEditingPolicy({ ...editingPolicy, medium_sla_days: parseInt(e.target.value) })}
                                                    className="w-full bg-blue-50/30 border-blue-100 rounded-lg px-3 py-2 text-sm font-bold focus:ring-blue-500 focus:border-blue-500"
                                                />
                                            </div>
                                            <div>
                                                <label className="block text-[10px] font-bold text-green-600 mb-1 uppercase">Low</label>
                                                <input
                                                    type="number"
                                                    value={editingPolicy.low_sla_days}
                                                    onChange={(e) => setEditingPolicy({ ...editingPolicy, low_sla_days: parseInt(e.target.value) })}
                                                    className="w-full bg-green-50/30 border-green-100 rounded-lg px-3 py-2 text-sm font-bold focus:ring-green-500 focus:border-green-500"
                                                />
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div className="flex justify-end gap-3 pt-6 border-t border-gray-50">
                                    <button
                                        type="button"
                                        onClick={() => setIsModalOpen(false)}
                                        className="px-6 py-2.5 text-sm font-bold text-gray-500 hover:text-gray-700 transition-colors"
                                    >
                                        Discard
                                    </button>
                                    <button
                                        type="submit"
                                        className="px-8 py-2.5 bg-vulncheck-blue text-white rounded-xl font-bold hover:bg-blue-700 transition-all shadow-lg shadow-blue-500/20"
                                    >
                                        Deploy Policy
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
