'use client';

import {useState} from 'react';
import {proportional, pixel} from '@astryxdesign/core/Table';
import {ResponsiveTable} from '@/shared/components/patterns/ResponsiveTable';
import type {TableColumn} from '@astryxdesign/core/Table';
import {VStack, HStack} from '@astryxdesign/core/Layout';
import {Text} from '@astryxdesign/core/Text';
import {Badge} from '@astryxdesign/core/Badge';
import {Button} from '@astryxdesign/core/Button';
import {Switch} from '@astryxdesign/core/Switch';
import {TextInput} from '@astryxdesign/core/TextInput';
import {useToast} from '@astryxdesign/core/Toast';
import {StaticPanel} from '@/shared/components/patterns/PanelCard';

export interface ActiveSessionItem extends Record<string, unknown> {
  id: string;
  device: string;
  location: string;
  ip: string;
  lastActive: string;
  isCurrent: boolean;
}

export interface LoginAuditItem extends Record<string, unknown> {
  id: string;
  user: string;
  ip: string;
  device: string;
  status: 'success' | 'failed';
  timestamp: string;
}

const INITIAL_SESSIONS: ActiveSessionItem[] = [
  {
    id: 'sess-1',
    device: 'macOS Chrome 126',
    location: 'Bengaluru, India',
    ip: '103.15.24.81',
    lastActive: 'Active Now',
    isCurrent: true,
  },
  {
    id: 'sess-2',
    device: 'iOS Safari 17',
    location: 'Bengaluru, India',
    ip: '49.207.210.12',
    lastActive: '2 hours ago',
    isCurrent: false,
  },
  {
    id: 'sess-3',
    device: 'Windows Edge 125',
    location: 'Bengaluru, India',
    ip: '106.51.72.19',
    lastActive: 'Yesterday, 18:40',
    isCurrent: false,
  },
];

const AUDIT_LOGS: LoginAuditItem[] = [
  {
    id: 'aud-1',
    user: 'aravind@nearle.in',
    ip: '103.15.24.81',
    device: 'macOS Chrome',
    status: 'success',
    timestamp: 'Today, 14:02',
  },
  {
    id: 'aud-2',
    user: 'vikram@nearle.in',
    ip: '106.51.72.19',
    device: 'Windows Chrome',
    status: 'success',
    timestamp: 'Today, 11:15',
  },
  {
    id: 'aud-3',
    user: 'aravind@nearle.in',
    ip: '185.220.101.5',
    device: 'Unknown Linux Device',
    status: 'failed',
    timestamp: 'Yesterday, 22:30',
  },
];

export function SecurityManager() {
  const toast = useToast();
  const [twoFactor, setTwoFactor] = useState(true);
  const [sessions, setSessions] = useState<ActiveSessionItem[]>(INITIAL_SESSIONS);
  const [currentPass, setCurrentPass] = useState('');
  const [newPass, setNewPass] = useState('');
  const [confirmPass, setConfirmPass] = useState('');
  const [isChangingPass, setIsChangingPass] = useState(false);

  const handleChangePassword = () => {
    if (!currentPass || !newPass) {
      toast({type: 'error', body: 'Please fill in all password fields'});
      return;
    }
    if (newPass !== confirmPass) {
      toast({type: 'error', body: 'New passwords do not match'});
      return;
    }
    setIsChangingPass(true);
    setTimeout(() => {
      setIsChangingPass(false);
      setCurrentPass('');
      setNewPass('');
      setConfirmPass('');
      toast({body: 'Password updated successfully'});
    }, 400);
  };

  const handleRevokeSession = (id: string) => {
    setSessions((prev) => prev.filter((s) => s.id !== id));
    toast({body: 'Session revoked successfully'});
  };

  const handleRevokeAllOther = () => {
    setSessions((prev) => prev.filter((s) => s.isCurrent));
    toast({body: 'All other active sessions have been terminated'});
  };

  const sessionColumns: TableColumn<ActiveSessionItem>[] = [
    {
      key: 'device',
      header: 'Device / Browser',
      width: proportional(2),
      renderCell: (row) => (
        <VStack gap={0}>
          <HStack gap={2} vAlign="center">
            <Text size="sm" weight="medium">
              {row.device}
            </Text>
            {row.isCurrent ? <Badge variant="success" label="Current Session" /> : null}
          </HStack>
          <Text size="sm" color="secondary">
            {row.location} • {row.ip}
          </Text>
        </VStack>
      ),
    },
    {
      key: 'lastActive',
      header: 'Last Active',
      width: proportional(1.2),
      renderCell: (row) => (
        <Text size="sm" color="secondary">
          {row.lastActive}
        </Text>
      ),
    },
    {
      key: 'actions',
      header: 'Action',
      align: 'center',
      width: pixel(120),
      renderCell: (row) =>
        row.isCurrent ? null : (
          <HStack hAlign="center">
            <Button
              size="sm"
              variant="ghost"
              label="Revoke"
              onClick={() => handleRevokeSession(row.id)}
            />
          </HStack>
        ),
    },
  ];

  const auditColumns: TableColumn<LoginAuditItem>[] = [
    {
      key: 'user',
      header: 'Account User',
      width: proportional(1.5),
      renderCell: (row) => (
        <Text size="sm" weight="medium">
          {row.user}
        </Text>
      ),
    },
    {
      key: 'device',
      header: 'Device & IP',
      width: proportional(2),
      renderCell: (row) => (
        <VStack gap={0}>
          <Text size="sm">{row.device}</Text>
          <Text size="sm" color="secondary">
            {row.ip}
          </Text>
        </VStack>
      ),
    },
    {
      key: 'status',
      header: 'Result',
      width: pixel(110),
      renderCell: (row) => (
        <Badge
          variant={row.status === 'success' ? 'success' : 'error'}
          label={row.status === 'success' ? 'Success' : 'Failed'}
        />
      ),
    },
    {
      key: 'timestamp',
      header: 'Timestamp',
      width: proportional(1.2),
      renderCell: (row) => (
        <Text size="sm" color="secondary">
          {row.timestamp}
        </Text>
      ),
    },
  ];

  return (
    <VStack gap={5}>
      <StaticPanel
        title="Two-Factor Authentication (2FA)"
        subtitle="Require an authenticator app code (TOTP) or SMS OTP during sign-in."
        actions={<Badge variant={twoFactor ? 'success' : 'warning'} label={twoFactor ? '2FA Enabled' : '2FA Disabled'} />}
      >
        <VStack gap={3}>
          <Switch
            label="Enable Two-Factor Authentication"
            description="Protect your merchant account with an extra verification step on new devices."
            value={twoFactor}
            onChange={(v) => {
              setTwoFactor(v);
              toast({body: `2FA ${v ? 'enabled' : 'disabled'}`});
            }}
          />
        </VStack>
      </StaticPanel>

      <StaticPanel
        title="Change Password"
        subtitle="Ensure your password is at least 12 characters long with mixed case and numbers."
        actions={
          <Button
            variant="primary"
            size="sm"
            label="Update Password"
            isLoading={isChangingPass}
            onClick={handleChangePassword}
          />
        }
      >
        <VStack gap={4}>
          <TextInput
            label="Current Password"
            type="password"
            value={currentPass}
            onChange={setCurrentPass}
          />
          <HStack gap={4} wrap="wrap">
            <TextInput
              label="New Password"
              type="password"
              value={newPass}
              onChange={setNewPass}
            />
            <TextInput
              label="Confirm New Password"
              type="password"
              value={confirmPass}
              onChange={setConfirmPass}
            />
          </HStack>
        </VStack>
      </StaticPanel>

      <StaticPanel
        title="Active Sessions"
        subtitle="Devices currently logged into your Loyaly merchant workspace."
        actions={
          <Button
            variant="secondary"
            size="sm"
            label="Revoke Other Sessions"
            onClick={handleRevokeAllOther}
          />
        }
      >
        <ResponsiveTable
            columns={sessionColumns}
            data={sessions}
            primaryKey="device"
          />
      </StaticPanel>

      <StaticPanel title="Login Audit Trail" subtitle="Recent account authentication events and security attempts.">
        <ResponsiveTable
            columns={auditColumns}
            data={AUDIT_LOGS}
            primaryKey="user"
          />
      </StaticPanel>
    </VStack>
  );
}
