'use client';

import React, { useState } from 'react';
import { Icon } from '@iconify/react';
import Link from 'next/link';
import { useEmailTemplates } from '@/modules/settings/hooks/useEmailTemplates';
import { deleteEmailTemplate } from '@/modules/settings/services/email-template.service';
import type { EmailTemplate } from '@/modules/settings/types';
import Swal from 'sweetalert2';
import { TestModal } from '../_components/TestModal';
import { useAbility } from '@/context/AuthContext';
import { RoleGuard } from '@/components/RoleGuard';
import { ButtonIcon } from '@/components/ButtonIcon';

export default function EmailTemplateListPage() {
  const { templates, isLoading, refetch } = useEmailTemplates();
  const [isTestModalOpen, setIsTestModalOpen] = useState(false);
  const [selectedTemplateCode, setSelectedTemplateCode] = useState<string | null>(null);

  const handleDelete = async (code: string) => {
    const result = await Swal.fire({
      title: 'Are you sure?',
      text: 'This will set the template to INACTIVE (Soft Delete).',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#00BFA5',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, soft delete it!',
    });

    if (result.isConfirmed) {
      try {
        await deleteEmailTemplate(code);
        Swal.fire('Deleted!', 'Template has been set to INACTIVE.', 'success');
        refetch();
      } catch (error: any) {
        Swal.fire('Error', error.message || 'Failed to delete template', 'error');
      }
    }
  };

  const ability = useAbility();

  const handleOpenTest = (code: string) => {
    setSelectedTemplateCode(code);
    setIsTestModalOpen(true);
  };

  return (
    <RoleGuard action="READ" resource="EmailTemplates">
      <div className="p-6">
        <div className="flex justify-between items-center mb-8">
          <div>
            <h1 className="text-2xl font-bold text-[var(--text-primary)]">Email Templates</h1>
            <p className="text-sm text-[var(--text-secondary)]">Manage your system email communications and dynamic templates.</p>
          </div>
          {ability.can('CREATE', 'EmailTemplates') && (
            <ButtonIcon
              text="Create Template"
              icon="add-circle-bold"
              href="/settings/email-templates/new"
              color="#00BFA5"
            />
          )}
        </div>

        <div className="bg-[var(--bg-paper)] rounded-3xl shadow-sm border border-[var(--border-default)] overflow-hidden">
          {isLoading ? (
            <div className="flex justify-center items-center p-20">
              <Icon icon="solar:spinner-bold" className="w-10 h-10 animate-spin text-primary" />
            </div>
          ) : templates.length === 0 ? (
            <div className="flex flex-col justify-center items-center p-20 text-center">
              <div className="p-6 bg-[var(--bg-default)] rounded-full mb-4">
                <Icon icon="solar:letter-bold-duotone" className="w-12 h-12 text-[var(--text-secondary)]/30" />
              </div>
              <h3 className="text-lg font-bold text-[var(--text-primary)]">No templates found</h3>
              <p className="text-sm text-[var(--text-secondary)] max-w-xs mx-auto">
                Get started by creating your first dynamic email template.
              </p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-left">
                <thead>
                  <tr className="bg-[var(--bg-default)] border-b border-[var(--border-default)]">
                    <th className="px-6 py-4 text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider">Code</th>
                    <th className="px-6 py-4 text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider">Name</th>
                    <th className="px-6 py-4 text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider">Subject</th>
                    <th className="px-6 py-4 text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider">Status</th>
                    <th className="px-6 py-4 text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider text-right">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[var(--border-default)]">
                  {templates.map((template) => (
                    <tr key={template.code} className="hover:bg-[var(--bg-default)] transition-colors group">
                      <td className="px-6 py-4">
                        <span className="text-xs font-mono font-bold bg-[var(--bg-default)] text-[var(--text-secondary)] px-2 py-1 rounded border border-[var(--border-default)]">
                          {template.code}
                        </span>
                      </td>
                      <td className="px-6 py-4">
                        <div className="text-sm font-bold text-[var(--text-primary)]">{template.name}</div>
                      </td>
                      <td className="px-6 py-4 max-w-xs">
                        <div className="text-sm text-[var(--text-secondary)] truncate">{template.subject}</div>
                      </td>
                      <td className="px-6 py-4">
                        <span
                          className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-bold ${template.status === 'ACTIVE'
                            ? 'bg-green-500/10 text-green-500'
                            : 'bg-red-500/10 text-red-500'
                            }`}
                        >
                          {template.status}
                        </span>
                      </td>
                      <td className="px-6 py-4 text-right">
                        <div className="flex justify-end items-center gap-2 transition-opacity">
                          {ability.can('EXECUTE', 'EmailTemplates') && (
                            <button
                              onClick={() => handleOpenTest(template.code)}
                              className="p-2 text-blue-500 hover:bg-blue-50 rounded-lg transition-colors"
                              title="Send Test Email"
                            >
                              <Icon icon="mdi:email-arrow-right" className="w-5 h-5" />
                            </button>
                          )}
                          {ability.can('UPDATE', 'EmailTemplates') && (
                            <Link
                              href={`/settings/email-templates/${template.code}/edit`}
                              className="p-2 text-primary hover:bg-primary/10 rounded-lg transition-colors"
                              title="Edit"
                            >
                              <Icon icon="solar:pen-bold-duotone" className="w-5 h-5" />
                            </Link>
                          )}
                          {ability.can('DELETE', 'EmailTemplates') && (
                            <button
                              onClick={() => handleDelete(template.code)}
                              className="p-2 text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                              title="Delete (Soft)"
                            >
                              <Icon icon="solar:trash-bin-trash-bold-duotone" className="w-5 h-5" />
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {isTestModalOpen && selectedTemplateCode && (
          <TestModal
            templateCode={selectedTemplateCode}
            onClose={() => setIsTestModalOpen(false)}
          />
        )}
      </div>
    </RoleGuard>
  );
}
