'use client';

import React, { useState } from 'react';
import { Button, Checkbox, Form, Input, Modal, Space, Tag, Tooltip } from 'antd';
import { Icon, type IconName } from '../ui/Icon';
import { CRM_MODULES, MODULE_META, SIDEBAR_MODULES, rolesApi, type CrmModule, type RolePermissionItem, type RoleRecord } from '../../lib/roles';

interface RoleModalProps {
  open: boolean;
  role: RoleRecord | null; // null means create mode
  onClose: () => void;
  onSuccess: (savedRole: RoleRecord) => void;
}

function initializeMatrix(existing?: RolePermissionItem[]) {
  const existingMap = new Map<string, RolePermissionItem>();
  (existing || []).forEach((p) => existingMap.set(p.module, p));

  const result = {} as Record<CrmModule, RolePermissionItem>;
  CRM_MODULES.forEach((mod) => {
    const found = existingMap.get(mod);
    result[mod] = {
      module: mod,
      canRead: found ? Boolean(found.canRead) : true,
      canCreate: found ? Boolean(found.canCreate) : false,
      canUpdate: found ? Boolean(found.canUpdate) : false,
      canDelete: found ? Boolean(found.canDelete) : false,
      canExport: found ? Boolean(found.canExport) : false,
    };
  });
  return result;
}

function RoleFormContent({ role, onClose, onSuccess }: { role: RoleRecord | null; onClose: () => void; onSuccess: (savedRole: RoleRecord) => void }) {
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);
  const isEdit = Boolean(role);

  // Keyed mount guarantees state initializes freshly without requiring an effect
  const [matrix, setMatrix] = useState<Record<CrmModule, RolePermissionItem>>(() => initializeMatrix(role?.permissions));

  const handleCellToggle = (module: CrmModule, action: 'canCreate' | 'canRead' | 'canUpdate' | 'canDelete' | 'canExport') => {
    setMatrix((prev) => {
      const current = prev[module];
      const nextVal = !current[action];
      const updated = { ...current, [action]: nextVal };

      // If enabling create, update, delete or export, automatically ensure canRead is true
      if (nextVal && action !== 'canRead') {
        updated.canRead = true;
      }
      // If disabling canRead, automatically disable create, update, delete, export
      if (!nextVal && action === 'canRead') {
        updated.canCreate = false;
        updated.canUpdate = false;
        updated.canDelete = false;
        updated.canExport = false;
      }

      return { ...prev, [module]: updated };
    });
  };

  const handleRowToggleAll = (module: CrmModule) => {
    setMatrix((prev) => {
      const current = prev[module];
      const allActive = current.canCreate && current.canRead && current.canUpdate && current.canDelete && current.canExport;
      const nextVal = !allActive;

      return {
        ...prev,
        [module]: {
          module,
          canRead: nextVal,
          canCreate: nextVal,
          canUpdate: nextVal,
          canDelete: nextVal,
          canExport: nextVal,
        },
      };
    });
  };

  const handleColumnToggleAll = (action: 'canCreate' | 'canRead' | 'canUpdate' | 'canDelete' | 'canExport') => {
    setMatrix((prev) => {
      const allChecked = CRM_MODULES.every((m) => prev[m][action]);
      const nextVal = !allChecked;

      const updated = { ...prev };
      CRM_MODULES.forEach((m) => {
        const item = { ...updated[m], [action]: nextVal };
        if (nextVal && action !== 'canRead') {
          item.canRead = true;
        }
        if (!nextVal && action === 'canRead') {
          item.canCreate = false;
          item.canUpdate = false;
          item.canDelete = false;
          item.canExport = false;
        }
        updated[m] = item;
      });
      return updated;
    });
  };

  const handleSelectAll = () => {
    setMatrix((prev) => {
      const updated = { ...prev };
      CRM_MODULES.forEach((m) => {
        updated[m] = {
          module: m,
          canRead: true,
          canCreate: true,
          canUpdate: true,
          canDelete: true,
          canExport: true,
        };
      });
      return updated;
    });
  };

  const handleReadOnlyPreset = () => {
    setMatrix((prev) => {
      const updated = { ...prev };
      CRM_MODULES.forEach((m) => {
        updated[m] = {
          module: m,
          canRead: m !== 'users_roles' && m !== 'roles',
          canCreate: false,
          canUpdate: false,
          canDelete: false,
          canExport: false,
        };
      });
      return updated;
    });
  };

  const handleClearAll = () => {
    setMatrix((prev) => {
      const updated = { ...prev };
      CRM_MODULES.forEach((m) => {
        updated[m] = {
          module: m,
          canRead: false,
          canCreate: false,
          canUpdate: false,
          canDelete: false,
          canExport: false,
        };
      });
      return updated;
    });
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setSubmitting(true);

      const permissionsArray = CRM_MODULES.map((m) => {
        if (m === 'contacts') return { ...matrix['accounts'], module: 'contacts' as CrmModule };
        if (m === 'timesheets') return { ...matrix['projects'], module: 'timesheets' as CrmModule };
        if (m === 'tasks' || m === 'activities') return { ...matrix['leads'], module: m as CrmModule };
        return matrix[m] || { module: m, canRead: false, canCreate: false, canUpdate: false, canDelete: false, canExport: false };
      });

      if (isEdit && role) {
        const updated = await rolesApi.update(role.id, {
          name: values.name,
          description: values.description,
          permissions: permissionsArray,
        });
        onSuccess(updated);
      } else {
        const created = await rolesApi.create({
          name: values.name,
          description: values.description,
          permissions: permissionsArray,
        });
        onSuccess(created);
      }
    } catch {
      // Form validation errors or API errors handled by caller
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div>
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          name: role?.name || '',
          description: role?.description || '',
        }}
        className="mt-4"
      >
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <Form.Item
            name="name"
            label="Role Name"
            rules={[
              { required: true, message: 'Please enter a role name' },
              { max: 100, message: 'Role name cannot exceed 100 characters' },
            ]}
          >
            <Input placeholder="Enter custom role title" disabled={role?.isSystem} />
          </Form.Item>

          <Form.Item name="description" label="Description">
            <Input placeholder="Short description of this role's purpose and scope" />
          </Form.Item>
        </div>

        {/* Matrix Controls & Presets */}
        <div className="mt-2 mb-3 flex flex-wrap items-center justify-between gap-2 border-t border-[var(--tcx-border)] pt-4">
          <div>
            <span className="text-[13px] font-semibold text-[var(--tcx-text)]">Module Permissions Matrix</span>
            <p className="mb-0 text-[11.5px] text-[var(--tcx-muted)]">Configure CRUD access for each CRM module. Read permission is required to create, edit, or delete.</p>
          </div>
          <Space size="small">
            <Button size="small" onClick={handleSelectAll}>
              Full Access
            </Button>
            <Button size="small" onClick={handleReadOnlyPreset}>
              Read Only
            </Button>
            <Button size="small" onClick={handleClearAll}>
              Clear
            </Button>
          </Space>
        </div>

        {/* Permissions Matrix Table */}
        <div className="overflow-x-auto rounded-lg border border-[var(--tcx-border)]">
          <table className="w-full text-left text-[12.5px]">
            <thead>
              <tr className="border-b border-[var(--tcx-border)] bg-[var(--tcx-surface-2)] text-[11px] font-semibold uppercase tracking-wider text-[var(--tcx-muted)]">
                <th className="px-4 py-2.5">Module</th>
                <th className="px-3 py-2.5 text-center">
                  <Tooltip title="Toggle View for all modules">
                    <button type="button" onClick={() => handleColumnToggleAll('canRead')} className="cursor-pointer font-semibold uppercase hover:text-[var(--tcx-primary)]">
                      View
                    </button>
                  </Tooltip>
                </th>
                <th className="px-3 py-2.5 text-center">
                  <Tooltip title="Toggle Create for all modules">
                    <button type="button" onClick={() => handleColumnToggleAll('canCreate')} className="cursor-pointer font-semibold uppercase hover:text-[var(--tcx-primary)]">
                      Create
                    </button>
                  </Tooltip>
                </th>
                <th className="px-3 py-2.5 text-center">
                  <Tooltip title="Toggle Edit for all modules">
                    <button type="button" onClick={() => handleColumnToggleAll('canUpdate')} className="cursor-pointer font-semibold uppercase hover:text-[var(--tcx-primary)]">
                      Edit
                    </button>
                  </Tooltip>
                </th>
                <th className="px-3 py-2.5 text-center">
                  <Tooltip title="Toggle Delete for all modules">
                    <button type="button" onClick={() => handleColumnToggleAll('canDelete')} className="cursor-pointer font-semibold uppercase hover:text-[var(--tcx-primary)]">
                      Delete
                    </button>
                  </Tooltip>
                </th>
                <th className="px-3 py-2.5 text-center">
                  <Tooltip title="Toggle Export for all modules">
                    <button type="button" onClick={() => handleColumnToggleAll('canExport')} className="cursor-pointer font-semibold uppercase hover:text-[var(--tcx-primary)]">
                      Export
                    </button>
                  </Tooltip>
                </th>
                <th className="px-3 py-2.5 text-center">All</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[var(--tcx-border)]">
              {SIDEBAR_MODULES.map((mod) => {
                const meta = MODULE_META[mod];
                const p = matrix[mod];
                const allChecked = p.canCreate && p.canRead && p.canUpdate && p.canDelete && p.canExport;
                const someChecked = (p.canCreate || p.canRead || p.canUpdate || p.canDelete || p.canExport) && !allChecked;

                return (
                  <tr key={mod} className="hover:bg-[var(--tcx-surface-2)]/50 transition-colors">
                    <td className="px-4 py-2">
                      <div className="flex items-center gap-2">
                        <Icon name={meta.icon as IconName} size={15} className="text-[var(--tcx-muted)]" />
                        <div>
                          <div className="font-medium text-[var(--tcx-text)]">{meta.label}</div>
                          <div className="text-[11px] text-[var(--tcx-muted)]">{meta.description}</div>
                        </div>
                      </div>
                    </td>
                    <td className="px-3 py-2 text-center">
                      <Checkbox checked={p.canRead} onChange={() => handleCellToggle(mod, 'canRead')} />
                    </td>
                    <td className="px-3 py-2 text-center">
                      <Checkbox checked={p.canCreate} onChange={() => handleCellToggle(mod, 'canCreate')} />
                    </td>
                    <td className="px-3 py-2 text-center">
                      <Checkbox checked={p.canUpdate} onChange={() => handleCellToggle(mod, 'canUpdate')} />
                    </td>
                    <td className="px-3 py-2 text-center">
                      <Checkbox checked={p.canDelete} onChange={() => handleCellToggle(mod, 'canDelete')} />
                    </td>
                    <td className="px-3 py-2 text-center">
                      <Checkbox checked={p.canExport} onChange={() => handleCellToggle(mod, 'canExport')} />
                    </td>
                    <td className="px-3 py-2 text-center">
                      <Checkbox indeterminate={someChecked} checked={allChecked} onChange={() => handleRowToggleAll(mod)} />
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Form>

      <div className="mt-5 flex justify-end gap-2 border-t border-[var(--tcx-border)] pt-4">
        <Button onClick={onClose} disabled={submitting}>
          Cancel
        </Button>
        <Button type="primary" loading={submitting} onClick={handleSubmit}>
          {isEdit ? 'Save Changes' : 'Create Role'}
        </Button>
      </div>
    </div>
  );
}

export function RoleModal({ open, role, onClose, onSuccess }: RoleModalProps) {
  const isEdit = Boolean(role);

  return (
    <Modal
      open={open}
      title={
        <div className="flex items-center gap-2">
          <Icon name="shield" size={18} className="text-[var(--tcx-primary)]" />
          <span className="text-[16px] font-semibold text-[var(--tcx-text)]">{isEdit ? `Edit Role: ${role?.name}` : 'Create New Custom Role'}</span>
          {role?.isSystem && <Tag color="blue">System Role</Tag>}
        </div>
      }
      onCancel={onClose}
      width={840}
      centered
      destroyOnHidden
      footer={null}
    >
      <RoleFormContent key={role ? role.id : 'new-role'} role={role} onClose={onClose} onSuccess={onSuccess} />
    </Modal>
  );
}
