import { Table, Input, Typography, Tag, Button } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { EmailTemplate, EmailTemplateVariable } from '@/types/api';
import { VideoCameraOutlined } from '@ant-design/icons';

const { Text } = Typography;

interface VariablesPanelProps {
  template: EmailTemplate;
  sampleData: Record<string, string>;
  onSampleDataChange: (data: Record<string, string>) => void;
}

export default function VariablesPanel({
  template,
  sampleData,
  onSampleDataChange,
}: VariablesPanelProps) {
  const variableColumns: ColumnsType<EmailTemplateVariable> = [
    {
      title: 'Type',
      dataIndex: 'type',
      width: 60,
      render: (type: string) => {
        if (type === 'VIDEO') {
          return (
            <Tag color="purple" icon={<VideoCameraOutlined />} style={{ fontSize: 10, margin: 0 }}>
              Video
            </Tag>
          );
        }
        return (
          <Tag style={{ fontSize: 10, margin: 0 }}>
            Text
          </Tag>
        );
      },
    },
    {
      title: 'Variable',
      dataIndex: 'key',
      width: 120,
      render: (key: string) => (
        <Text code style={{ fontSize: 11 }}>
          {'{{' + key + '}}'}
        </Text>
      ),
    },
    {
      title: 'Label',
      dataIndex: 'label',
      width: 100,
    },
    {
      title: 'Description',
      dataIndex: 'description',
      ellipsis: { showTitle: false },
      render: (desc: string | null) => (
        <Text
          type="secondary"
          ellipsis={{ tooltip: desc || undefined }}
          style={{ fontSize: 12 }}
        >
          {desc || '—'}
        </Text>
      ),
    },
    {
      title: 'Req',
      dataIndex: 'isRequired',
      width: 40,
      align: 'center',
      render: (isRequired: boolean) =>
        isRequired ? (
          <Tag color="red" style={{ fontSize: 10, margin: 0 }}>
            Req
          </Tag>
        ) : null,
    },
  ];

  return (
    <div
      style={{ display: 'flex', flexDirection: 'column', height: 'calc(100vh - 110px)' }}
    >
      {/* Variables Reference Table - Top Half */}
      <div
        style={{
          flex: '1 1 50%',
          display: 'flex',
          flexDirection: 'column',
          borderBottom: '1px solid #d9d9d9',
          overflow: 'hidden',
        }}
      >
        <div style={{ padding: '6px 12px', backgroundColor: '#fafafa', flexShrink: 0 }}>
          <Text strong style={{ fontSize: 12 }}>Available Variables</Text>
        </div>
        <div style={{ flex: 1, overflow: 'auto' }}>
          <Table
            dataSource={template.variables}
            columns={variableColumns}
            rowKey="id"
            size="small"
            pagination={false}
          />
        </div>
      </div>

      {/* Sample Data Inputs - Bottom Half */}
      <div style={{ flex: '1 1 50%', padding: 12, overflow: 'auto' }}>
        <Text strong style={{ display: 'block', marginBottom: 8, fontSize: 12 }}>
          Sample Data (for preview)
        </Text>
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: template.variables.length > 4 ? '1fr 1fr' : '1fr',
            gap: 10,
          }}
        >
          {template.variables.map((v) => {
            // VIDEO variables show preview link instead of input
            if (v.type === 'VIDEO') {
              const mediaApiUrl = import.meta.env.VITE_MEDIA_API_URL || 'http://localhost:4100';
              return (
                <div key={v.key}>
                  <Text
                    type="secondary"
                    style={{
                      fontSize: 11,
                      display: 'block',
                      marginBottom: 3,
                    }}
                  >
                    {v.label}
                  </Text>
                  <Input
                    size="small"
                    value={`Video ID: ${v.videoId}`}
                    disabled
                    addonAfter={
                      <Button
                        size="small"
                        type="link"
                        onClick={() => {
                          window.open(`${mediaApiUrl}/api/videos/${v.videoId}/metadata`, '_blank');
                        }}
                        style={{ padding: 0 }}
                      >
                        Preview
                      </Button>
                    }
                  />
                </div>
              );
            }

            // TEXT variables show standard input
            return (
              <div key={v.key}>
                <Text
                  type="secondary"
                  style={{
                    fontSize: 11,
                    display: 'block',
                    marginBottom: 3,
                  }}
                >
                  {v.label}
                </Text>
                <Input
                  size="small"
                  value={sampleData[v.key] || ''}
                  onChange={(e) =>
                    onSampleDataChange({ ...sampleData, [v.key]: e.target.value })
                  }
                  placeholder={v.sampleValue || ''}
                />
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
