import { useState } from 'react';
import { Button, Input, Space, Typography, message, Alert, Dropdown, Modal, Row, Col, Grid } from 'antd';
import { FormOutlined, ArrowRightOutlined, WarningOutlined } from '@ant-design/icons';
import type { VisitOutcome, RecordVisitPayload, BulkRecordVisitPayload, CanvassAddress } from '@/types/canvass';
import type { SupportLevel, UserRole } from '@/types/api';
import { VISIT_OUTCOME_LABELS, VISIT_OUTCOME_COLORS } from '@/types/canvass';
import { SUPPORT_LEVEL_LABELS, SUPPORT_LEVEL_COLORS } from '@/types/api';
import { sanitizeHtml } from '@/utils/sanitize';

interface VisitRecordingFormProps {
  address: CanvassAddress;
  sessionId?: string;
  shiftId?: string;
  onRecord: (payload: RecordVisitPayload) => Promise<void>;
  onBulkRecord?: (payload: BulkRecordVisitPayload) => Promise<void>;
  onNextUnit?: () => void;
  recording: boolean;
  userRole?: UserRole;
  isMultiUnit?: boolean;
  unvisitedCountInBuilding?: number;
}

const outcomeKeys: VisitOutcome[] = [
  'SPOKE_WITH',
  'NOT_HOME',
  'REFUSED',
  'LEFT_LITERATURE',
  'COME_BACK_LATER',
  'MOVED',
  'ALREADY_VOTED',
];

const supportLevelKeys: SupportLevel[] = ['LEVEL_1', 'LEVEL_2', 'LEVEL_3', 'LEVEL_4'];

export default function VisitRecordingForm({
  address,
  sessionId,
  shiftId,
  onRecord,
  onBulkRecord,
  onNextUnit,
  recording,
  userRole,
  isMultiUnit = false,
  unvisitedCountInBuilding = 0,
}: VisitRecordingFormProps) {
  const [outcome, setOutcome] = useState<VisitOutcome | null>(null);
  const [supportLevel, setSupportLevel] = useState<SupportLevel | undefined>(undefined);
  const [signRequested, setSignRequested] = useState(false);
  const [signSize, setSignSize] = useState<string | undefined>(undefined);
  const [notes, setNotes] = useState('');
  const screens = Grid.useBreakpoint();
  const isNarrow = !screens.sm;

  const showDetailFields = userRole !== 'TEMP';

  const handleSubmit = async () => {
    if (!outcome) {
      message.warning('Select an outcome');
      return;
    }

    await onRecord({
      addressId: address.id, // Changed from locationId
      outcome,
      supportLevel,
      signRequested,
      signSize,
      notes: notes || undefined,
      sessionId,
      shiftId,
    });

    // Auto-advance to next unit if multi-unit
    if (isMultiUnit && unvisitedCountInBuilding > 1 && onNextUnit) {
      onNextUnit();
    }

    // Reset form
    setOutcome(null);
    setSupportLevel(undefined);
    setSignRequested(false);
    setSignSize(undefined);
    setNotes('');
  };

  const handleBulkRecord = (bulkOutcome: 'NOT_HOME' | 'REFUSED' | 'MOVED') => {
    if (!onBulkRecord) return;

    Modal.confirm({
      title: (
        <span style={{ color: '#ff4d4f' }}>
          ⚠️ Bulk Record Visit
        </span>
      ),
      icon: <WarningOutlined style={{ color: '#ff4d4f' }} />,
      content: (
        <div>
          <p>
            This will mark <strong style={{ color: '#ff4d4f' }}>ALL {unvisitedCountInBuilding} unvisited units</strong> in this building as:
          </p>
          <p style={{ fontSize: 16, fontWeight: 600, color: '#ff4d4f', margin: '12px 0' }}>
            {bulkOutcome.replace(/_/g, ' ')}
          </p>
          <p style={{ fontSize: 12, color: '#666', marginTop: 8 }}>
            This action will record {unvisitedCountInBuilding} separate visit entries and cannot be easily undone.
          </p>
        </div>
      ),
      okText: `Record ${unvisitedCountInBuilding} Visits`,
      okType: 'danger',
      okButtonProps: { danger: true },
      cancelText: 'Cancel',
      onOk: async () => {
        await onBulkRecord({
          locationId: address.location.id,
          outcome: bulkOutcome,
          notes,
          sessionId,
          shiftId,
        });
      },
    });
  };

  return (
    <div style={{ padding: '0 4px' }}>
      {address.firstName && (
        <Typography.Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
          {address.firstName} {address.lastName}
        </Typography.Text>
      )}

      {/* Building notes for multi-unit */}
      {address.location.buildingNotes && (
        <Alert
          message="Building Notes"
          description={
            <div dangerouslySetInnerHTML={{ __html: sanitizeHtml(address.location.buildingNotes) }} />
          }
          type="info"
          showIcon
          banner
          closable
          style={{ marginBottom: 12, fontSize: 11 }}
        />
      )}

      <Typography.Text
        strong
        style={{
          display: 'block',
          marginBottom: 8,
          fontSize: 13,
          textTransform: 'uppercase',
          letterSpacing: 0.5,
        }}
      >
        Visit Outcome
      </Typography.Text>
      <Row gutter={[6, 6]} style={{ marginBottom: 12 }}>
        {outcomeKeys.map((key) => {
          const color = VISIT_OUTCOME_COLORS[key];
          const selected = outcome === key;
          return (
            <Col
              key={key}
              xs={isNarrow ? 12 : 8}
              sm={8}
              md={6}
            >
              <Button
                block
                size="large"
                type={selected ? 'primary' : 'default'}
                style={{
                  borderColor: color,
                  background: selected ? color : 'transparent',
                  color: selected ? '#fff' : color,
                  fontSize: 12,
                  fontWeight: key === 'SPOKE_WITH' ? 600 : 400,
                }}
                onClick={() => setOutcome(key)}
              >
                {VISIT_OUTCOME_LABELS[key]}
              </Button>
            </Col>
          );
        })}
      </Row>

      {showDetailFields && outcome === 'SPOKE_WITH' && (
        <>
          <Typography.Text
            strong
            style={{
              display: 'block',
              marginTop: 16,
              marginBottom: 8,
              fontSize: 13,
              textTransform: 'uppercase',
              letterSpacing: 0.5,
            }}
          >
            Support Level
          </Typography.Text>
          <Row gutter={[8, 8]} justify="space-between" style={{ marginBottom: 12 }}>
            {supportLevelKeys.map((key) => (
              <Col key={key} xs={6} sm={6}>
                <div style={{ textAlign: 'center' }}>
                  <Button
                    shape="circle"
                    size="large"
                    type={supportLevel === key ? 'primary' : 'default'}
                    style={{
                      width: 48,
                      height: 48,
                      background: supportLevel === key ? SUPPORT_LEVEL_COLORS[key] : undefined,
                      borderColor: SUPPORT_LEVEL_COLORS[key],
                      color: supportLevel === key ? '#fff' : SUPPORT_LEVEL_COLORS[key],
                      fontWeight: 700,
                    }}
                    onClick={() => setSupportLevel(supportLevel === key ? undefined : key)}
                  >
                    {key.replace('LEVEL_', '')}
                  </Button>
                  <div style={{ fontSize: 11, marginTop: 4, color: 'rgba(255,255,255,0.6)' }}>
                    {SUPPORT_LEVEL_LABELS[key]}
                  </div>
                </div>
              </Col>
            ))}
          </Row>

          <Typography.Text
            strong
            style={{
              display: 'block',
              marginTop: 16,
              marginBottom: 8,
              fontSize: 13,
              textTransform: 'uppercase',
              letterSpacing: 0.5,
            }}
          >
            Sign Request
          </Typography.Text>
          <Space style={{ marginBottom: 12 }}>
            <Button
              type={signRequested ? 'primary' : 'default'}
              onClick={() => { setSignRequested(!signRequested); if (signRequested) setSignSize(undefined); }}
            >
              {signRequested ? 'Yes' : 'No Sign'}
            </Button>
            {signRequested && (
              <>
                {['Regular', 'Large', 'Unsure'].map((size) => (
                  <Button
                    key={size}
                    type={signSize === size ? 'primary' : 'default'}
                    onClick={() => setSignSize(size)}
                    size="small"
                  >
                    {size}
                  </Button>
                ))}
              </>
            )}
          </Space>
        </>
      )}

      {showDetailFields && (
        <>
          <Typography.Text
            strong
            style={{
              display: 'block',
              marginTop: 16,
              marginBottom: 8,
              fontSize: 13,
              textTransform: 'uppercase',
              letterSpacing: 0.5,
            }}
          >
            Notes (Optional)
          </Typography.Text>
          <Input.TextArea
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            rows={2}
            placeholder="Optional notes..."
            style={{ marginBottom: 12 }}
          />
        </>
      )}

      <Space style={{ width: '100%' }} direction="vertical" size="small">
        <Button
          type="primary"
          block
          size="large"
          onClick={handleSubmit}
          loading={recording}
          disabled={!outcome}
        >
          Record Visit
        </Button>

        {/* Bulk record and next unit buttons for multi-unit */}
        {isMultiUnit && unvisitedCountInBuilding > 1 && (
          <Row gutter={[8, 8]} style={{ width: '100%' }}>
            {/* Bulk record dropdown */}
            {onBulkRecord && (
              <Col xs={24} sm={12}>
                <Dropdown
                  menu={{
                    items: [
                      {
                        key: 'NOT_HOME',
                        label: `All Not Home (${unvisitedCountInBuilding})`,
                        onClick: () => handleBulkRecord('NOT_HOME'),
                      },
                      {
                        key: 'REFUSED',
                        label: `All Refused (${unvisitedCountInBuilding})`,
                        onClick: () => handleBulkRecord('REFUSED'),
                      },
                      {
                        key: 'MOVED',
                        label: `All Moved (${unvisitedCountInBuilding})`,
                        onClick: () => handleBulkRecord('MOVED'),
                      },
                    ],
                  }}
                >
                  <Button icon={<FormOutlined />} size="middle" block>
                    Record All Units
                  </Button>
                </Dropdown>
              </Col>
            )}

            {/* Next unit button */}
            {onNextUnit && (
              <Col xs={24} sm={12}>
                <Button icon={<ArrowRightOutlined />} onClick={onNextUnit} size="middle" block>
                  Next Unit
                </Button>
              </Col>
            )}
          </Row>
        )}
      </Space>
    </div>
  );
}
