import {
  List,
  ShowButton,
  useTable,
  EditButton,
  TagField,
} from "@refinedev/antd";
import type { BaseRecord } from "@refinedev/core";
import { Space, Table, Tag, Badge, Typography, Input, Select, Button } from "antd";
import { SearchOutlined, FilterOutlined } from '@ant-design/icons';
import { useState } from "react";

const { Title } = Typography;

export const SupportTickets = () => {
  const [searchText, setSearchText] = useState("");
  const [priorityFilter, setPriorityFilter] = useState("all");
  const [statusFilter, setStatusFilter] = useState("all");

  const { tableProps } = useTable({
    syncWithLocation: true,
    filters: {
      // Add server-side filters based on local state if API supports it
    }
  });

  // Simulate client-side filtering for demo purposes
  // In a real app, this would be done on server side
  const filteredData = tableProps?.dataSource?.filter((ticket: any) => {
    let matches = true;
    
    if (searchText) {
      const searchLower = searchText.toLowerCase();
      matches = matches && (
        ticket?.title?.toLowerCase().includes(searchLower) || 
        ticket?.description?.toLowerCase().includes(searchLower)
      );
    }
    
    if (priorityFilter !== "all") {
      matches = matches && ticket?.priority === priorityFilter;
    }
    
    if (statusFilter !== "all") {
      matches = matches && ticket?.status === statusFilter;
    }
    
    return matches;
  });

  const priorityColors = {
    low: 'blue',
    medium: 'orange',
    high: 'red',
    critical: 'purple'
  };

  const statusColors = {
    open: 'green',
    'in-progress': 'blue',
    resolved: 'gray',
    closed: 'black'
  };

  return (
    <>
      <Title level={4}>Support Tickets</Title>
      
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <Space>
          <Input
            placeholder="Search tickets"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            style={{ width: 200 }}
            allowClear
          />
          
          <Select 
            style={{ width: 120 }} 
            defaultValue="all"
            onChange={(value) => setPriorityFilter(value)} 
            placeholder="Priority"
          >
            <Select.Option value="all">All Priorities</Select.Option>
            <Select.Option value="low">Low</Select.Option>
            <Select.Option value="medium">Medium</Select.Option>
            <Select.Option value="high">High</Select.Option>
            <Select.Option value="critical">Critical</Select.Option>
          </Select>
          
          <Select 
            style={{ width: 120 }} 
            defaultValue="all"
            onChange={(value) => setStatusFilter(value)} 
            placeholder="Status"
          >
            <Select.Option value="all">All Statuses</Select.Option>
            <Select.Option value="open">Open</Select.Option>
            <Select.Option value="in-progress">In Progress</Select.Option>
            <Select.Option value="resolved">Resolved</Select.Option>
            <Select.Option value="closed">Closed</Select.Option>
          </Select>
        </Space>
        
        <Button type="primary">Create Ticket</Button>
      </div>
      
      <List>
        <Table 
          {...tableProps} 
          dataSource={filteredData || tableProps.dataSource} 
          rowKey="id"
          pagination={{ pageSize: 10 }}
        >
          <Table.Column dataIndex="id" title="Ticket ID" />
          <Table.Column dataIndex="title" title="Title" />
          <Table.Column 
            dataIndex="clientName" 
            title="Client" 
            render={(value, record: any) => (
              <span>
                {value}
                {record.clientId && <div style={{ fontSize: '12px', color: '#888' }}>ID: {record.clientId}</div>}
              </span>
            )}
          />
          <Table.Column 
            dataIndex="priority" 
            title="Priority" 
            render={(value) => (
              <Tag color={priorityColors[value as keyof typeof priorityColors] || 'default'}>
                {value?.toUpperCase()}
              </Tag>
            )}
          />
          <Table.Column 
            dataIndex="status" 
            title="Status" 
            render={(value) => (
              <Badge 
                color={statusColors[value as keyof typeof statusColors] || 'default'} 
                text={value?.replace('-', ' ')} 
              />
            )}
          />
          <Table.Column 
            dataIndex="category" 
            title="Category" 
            render={(value) => (
              <TagField value={value} />
            )}
          />
          <Table.Column dataIndex="createdAt" title="Created" />
          <Table.Column
            title="Actions"
            dataIndex="actions"
            render={(_, record: BaseRecord) => (
              <Space>
                <ShowButton hideText size="small" recordItemId={record.id} />
                <EditButton hideText size="small" recordItemId={record.id} />
                <Button type="primary" size="small">
                  Respond
                </Button>
              </Space>
            )}
          />
        </Table>
      </List>
    </>
  );
};