import { useState, useMemo, useEffect, CSSProperties } from 'react';
import { Layout, Menu, Row, Col, Card, Statistic, Button, Typography, Alert, Space, List, Avatar, Badge, Spin, message } from 'antd';
import {
  DashboardOutlined,
  UserOutlined,
  SettingOutlined,
  BankOutlined,
  FileSearchOutlined,
  BarChartOutlined,
  ReloadOutlined,
  TeamOutlined,
  BookOutlined,
  CopyOutlined,
  SwapOutlined,
  WarningOutlined
} from '@ant-design/icons';
import { request } from '../api/client';
import { useNavigate } from 'react-router-dom';

interface UserResponse {
  id: string;
  email: string;
  first_name: string;
  last_name: string;
}

interface MemberResponse {
  id: string;
  membership_number: string;
  user: UserResponse;
}

interface BookAuthorResponse {
  author_id: string;
  author_order: number | null;
}

interface BookResponse {
  id: string;
  title: string;
  book_authors: BookAuthorResponse[];
}

interface BookCopyResponse {
  id: string;
  book_id: string;
  barcode: string;
  library_branch_id: string;
  condition_status: 'EXCELLENT' | 'GOOD' | 'FAIR' | 'POOR' | 'DAMAGED' | 'LOST';
  availability_status: 'AVAILABLE' | 'CHECKED_OUT' | 'RESERVED' | 'IN_TRANSIT' | 'MAINTENANCE' | 'LOST';
}

interface LoanResponse {
  id: string;
  member_id: string;
  book_copy_id: string;
  checkout_date: string;
  due_date: string;
  return_date: string | null;
  renewal_count: number;
  status: 'ACTIVE' | 'RETURNED' | 'OVERDUE' | 'LOST';
  checked_out_by_librarian_id: string | null;
  checked_in_by_librarian_id: string | null;
  notes: string | null;
  created_at: string;
  updated_at: string;
}

interface PaymentResponse {
  id: string;
  member_id: string;
  fine_id: string | null;
  amount: string;
  payment_method: 'CASH' | 'CREDIT_CARD' | 'DEBIT_CARD' | 'ONLINE' | 'CHECK';
  transaction_date: string;
  reference_number: string | null;
  processed_by_librarian_id: string | null;
  notes: string | null;
  created_at: string;
  updated_at: string;
}

interface AuditLogResponse {
  id: string;
  user_id: string | null;
  action_type: string;
  entity_type: string | null;
  entity_id: string | null;
  timestamp: string;
  ip_address: string | null;
  details: Record<string, unknown> | null;
  created_at: string;
  updated_at: string;
}

interface LibraryBranchResponse {
  id: string;
  name: string;
  address: string;
  phone: string | null;
  email: string | null;
  operating_hours: string | null;
  created_at: string;
  updated_at: string;
}

export default function AdminDashboardPage() {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();

  const [members, setMembers] = useState<MemberResponse[]>([]);
  const [books, setBooks] = useState<BookResponse[]>([]);
  const [bookCopies, setBookCopies] = useState<BookCopyResponse[]>([]);
  const [activeLoans, setActiveLoans] = useState<LoanResponse[]>([]);
  const [overdueLoans, setOverdueLoans] = useState<LoanResponse[]>([]);
  const [recentPayments, setRecentPayments] = useState<PaymentResponse[]>([]);
  const [auditLogs, setAuditLogs] = useState<AuditLogResponse[]>([]);
  const [branches, setBranches] = useState<LibraryBranchResponse[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  const totalMembers = useMemo(() => members.length, [members]);
  const totalBooks = useMemo(() => books.length, [books]);
  const totalCopies = useMemo(() => bookCopies.length, [bookCopies]);
  const activeLoansCount = useMemo(() => activeLoans.length, [activeLoans]);
  const overdueCount = useMemo(() => overdueLoans.length, [overdueLoans]);
  const monthlyRevenue = useMemo(
    () => recentPayments.reduce((sum, p) => sum + Number(p.amount), 0),
    [recentPayments]
  );
  const systemHealthStatus = useMemo(
    () => (overdueLoans.length > 50 ? 'critical' : overdueLoans.length > 20 ? 'warning' : 'healthy'),
    [overdueLoans]
  );

  const fetchAllData = async () => {
    setLoading(true);
    try {
      const [
        membersRes,
        booksRes,
        copiesRes,
        activeLoansRes,
        overdueLoansRes,
        paymentsRes,
        auditLogsRes,
        branchesRes
      ] = await Promise.all([
        request<MemberResponse[]>({
          method: 'GET',
          path: '/auth/members',
          query: { limit: 50, offset: 0 }
        }),
        request<BookResponse[]>({
          method: 'GET',
          path: '/catalog/books',
          query: { limit: 50, offset: 0 }
        }),
        request<BookCopyResponse[]>({
          method: 'GET',
          path: '/catalog/book-copies',
          query: { limit: 50, offset: 0 }
        }),
        request<LoanResponse[]>({
          method: 'GET',
          path: '/loans/',
          query: { limit: 50, offset: 0, status: 'ACTIVE' }
        }),
        request<LoanResponse[]>({
          method: 'GET',
          path: '/loans/',
          query: { limit: 50, offset: 0, status: 'OVERDUE' }
        }),
        request<PaymentResponse[]>({
          method: 'GET',
          path: '/fines/payments',
          query: { limit: 50, offset: 0 }
        }),
        request<AuditLogResponse[]>({
          method: 'GET',
          path: '/system/audit-logs',
          query: { limit: 20, offset: 0 }
        }),
        request<LibraryBranchResponse[]>({
          method: 'GET',
          path: '/library-branches/',
          query: { limit: 20, offset: 0 }
        })
      ]);

      setMembers(membersRes.data);
      setBooks(booksRes.data);
      setBookCopies(copiesRes.data);
      setActiveLoans(activeLoansRes.data);
      setOverdueLoans(overdueLoansRes.data);
      setRecentPayments(paymentsRes.data);
      setAuditLogs(auditLogsRes.data);
      setBranches(branchesRes.data);
    } catch (error) {
      messageApi.error('Failed to load dashboard data');
    } finally {
      setLoading(false);
    }
  };

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

  const navigateToUserManagement = () => {
    navigate('/admin/users');
  };

  const navigateToSystemConfig = () => {
    navigate('/admin/configuration');
  };

  const navigateToBranchManagement = () => {
    navigate('/admin/branches');
  };

  const navigateToAuditLogs = () => {
    navigate('/admin/audit-logs');
  };

  const navigateToReports = () => {
    navigate('/staff/reports');
  };

  const refreshDashboard = async () => {
    await fetchAllData();
    messageApi.success('Dashboard refreshed');
  };

  const handleMenuClick = ({ key }: { key: string }) => {
    switch (key) {
      case 'users':
        navigateToUserManagement();
        break;
      case 'config':
        navigateToSystemConfig();
        break;
      case 'branches':
        navigateToBranchManagement();
        break;
      case 'audit':
        navigateToAuditLogs();
        break;
      case 'reports':
        navigateToReports();
        break;
      default:
        break;
    }
  };

  const menuItems = [
    {
      key: 'dashboard',
      label: 'Dashboard',
      icon: <DashboardOutlined />
    },
    {
      key: 'users',
      label: 'User Management',
      icon: <UserOutlined />
    },
    {
      key: 'config',
      label: 'System Configuration',
      icon: <SettingOutlined />
    },
    {
      key: 'branches',
      label: 'Branch Management',
      icon: <BankOutlined />
    },
    {
      key: 'audit',
      label: 'Audit Logs',
      icon: <FileSearchOutlined />
    },
    {
      key: 'reports',
      label: 'Reports & Analytics',
      icon: <BarChartOutlined />
    }
  ];

  const rootStyle: CSSProperties = {
    minHeight: '100vh',
    height: '100%',
    width: '100%',
    display: 'flex',
    flexDirection: 'row'
  };

  const contentStyle: CSSProperties = {
    padding: '24px',
    background: '#f5f5f5'
  };

  const pageHeaderStyle: CSSProperties = {
    marginBottom: '24px',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center'
  };

  const siderStyle: CSSProperties = {
    borderRight: '1px solid #f0f0f0'
  };

  return (
    <div style={rootStyle}>
      {contextHolder}
      <Layout.Sider width={250} collapsible theme="light" style={siderStyle}>
        <Menu
          mode="inline"
          items={menuItems}
          defaultSelectedKeys={['dashboard']}
          onClick={handleMenuClick}
        />
      </Layout.Sider>
      <Layout.Content style={contentStyle}>
        <Spin spinning={loading}>
          <div style={pageHeaderStyle}>
            <Typography.Title level={2} style={{ margin: 0 }}>
              Admin Dashboard
            </Typography.Title>
            <Button type="default" icon={<ReloadOutlined />} onClick={refreshDashboard}>
              Refresh
            </Button>
          </div>

          <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
            <Col xs={24} sm={12} md={8} lg={6}>
              <Card size="small">
                <Statistic
                  title="Total Members"
                  value={totalMembers}
                  prefix={<TeamOutlined />}
                  valueStyle={{ color: '#1677ff' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={8} lg={6}>
              <Card size="small">
                <Statistic
                  title="Total Books"
                  value={totalBooks}
                  prefix={<BookOutlined />}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={8} lg={6}>
              <Card size="small">
                <Statistic
                  title="Total Copies"
                  value={totalCopies}
                  prefix={<CopyOutlined />}
                  valueStyle={{ color: '#722ed1' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={8} lg={6}>
              <Card size="small">
                <Statistic
                  title="Active Loans"
                  value={activeLoansCount}
                  prefix={<SwapOutlined />}
                  valueStyle={{ color: '#fa8c16' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={8} lg={6}>
              <Card size="small">
                <Statistic
                  title="Overdue Books"
                  value={overdueCount}
                  prefix={<WarningOutlined />}
                  valueStyle={{ color: '#ff4d4f' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={8} lg={6}>
              <Card size="small">
                <Statistic
                  title="Revenue (Month)"
                  value={monthlyRevenue}
                  prefix="$"
                  precision={2}
                  valueStyle={{ color: '#13c2c2' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={8} lg={6}>
              <Card size="small">
                <Badge
                  status={systemHealthStatus === 'healthy' ? 'success' : systemHealthStatus === 'warning' ? 'warning' : 'error'}
                  text="System Health"
                  style={{ fontSize: '16px' }}
                />
              </Card>
            </Col>
          </Row>

          <Row gutter={[16, 16]}>
            <Col xs={24} lg={14}>
              <Card title="Recent Activity" size="default" style={{ height: '100%' }}>
                <List
                  size="small"
                  dataSource={auditLogs}
                  pagination={{ pageSize: 8 }}
                  renderItem={(item) => (
                    <List.Item>
                      <List.Item.Meta
                        avatar={<Avatar icon={<UserOutlined />} />}
                        title={item.action_type}
                        description={new Date(item.timestamp).toLocaleString()}
                      />
                    </List.Item>
                  )}
                />
              </Card>
            </Col>
            <Col xs={24} lg={10}>
              <Card title="System Alerts" size="default" style={{ marginBottom: '16px' }}>
                {overdueCount > 0 && (
                  <Alert
                    type="warning"
                    message="Overdue Books Alert"
                    description={`There are ${overdueCount} overdue books requiring attention.`}
                    showIcon
                    style={{ marginBottom: '12px' }}
                  />
                )}
                <Alert
                  type={systemHealthStatus === 'healthy' ? 'success' : systemHealthStatus === 'warning' ? 'warning' : 'error'}
                  message="System Status"
                  description={
                    systemHealthStatus === 'healthy'
                      ? 'All systems operational.'
                      : systemHealthStatus === 'warning'
                      ? 'System requires attention.'
                      : 'Critical system issues detected.'
                  }
                  showIcon
                  style={{ marginBottom: '12px' }}
                />
              </Card>
              <Card title="Quick Links" size="default">
                <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                  <Button type="default" block icon={<UserOutlined />} onClick={navigateToUserManagement}>
                    User Management
                  </Button>
                  <Button type="default" block icon={<SettingOutlined />} onClick={navigateToSystemConfig}>
                    System Configuration
                  </Button>
                  <Button type="default" block icon={<BankOutlined />} onClick={navigateToBranchManagement}>
                    Branch Management
                  </Button>
                  <Button type="default" block icon={<FileSearchOutlined />} onClick={navigateToAuditLogs}>
                    Audit Logs
                  </Button>
                  <Button type="default" block icon={<BarChartOutlined />} onClick={navigateToReports}>
                    Reports & Analytics
                  </Button>
                </Space>
              </Card>
            </Col>
          </Row>
        </Spin>
      </Layout.Content>
    </div>
  );
}