import { useEffect, useMemo, useState } from 'react'
import { Table, Switch, Select, Input, Button, Tag, Pagination } from 'antd'
import { LoadingOutlined } from '@ant-design/icons'
import Layout from '../../layout/HealthHubLayout'
import { getAuthCookie } from '../../api/axiosInstance'
import {
  useGetSmsSettings,
  useUpdateSmsSettings,
  useSendTestSms,
  useGetSmsLogs,
  useBroadcastSms,
  SmsSettings as SmsSettingsType,
  SmsTemplate,
} from '../../api/hooks/useSmsSettings'

// Fixed display order of the message types
const MESSAGE_TYPE_ORDER = ['announcement', 'birthday', 'appointment_reminder', 'general_notification']

const { TextArea } = Input

const DRIVER_LABELS: Record<string, string> = {
  termii: 'Termii (Nigeria)',
  africastalking: "Africa's Talking",
  log: 'Log only (no real SMS — for testing)',
}

const Card: React.FC<{ title?: string; description?: string; children: React.ReactNode }> = ({
  title,
  description,
  children,
}) => (
  <div className="rounded-[14px] bg-white p-4 md:p-6 mb-4 md:mb-6">
    {title && <h3 className="text-lg md:text-xl font-bold text-[#030229] mb-1">{title}</h3>}
    {description && <p className="text-sm text-gray-500 mb-4">{description}</p>}
    {children}
  </div>
)

const Field: React.FC<{ label: string; hint?: string; children: React.ReactNode }> = ({
  label,
  hint,
  children,
}) => (
  <div className="flex flex-col gap-1.5">
    <label className="text-[#666666] text-[14px] font-medium">{label}</label>
    {children}
    {hint && <span className="text-xs text-gray-400">{hint}</span>}
  </div>
)

const SmsSettingsPage = () => {
  const { data, isLoading, error } = useGetSmsSettings()
  const updateMutation = useUpdateSmsSettings()
  const testMutation = useSendTestSms()
  const broadcastMutation = useBroadcastSms()

  // The SMS Gateway card exposes provider credentials (API key) — restrict it to super admin.
  const role = getAuthCookie()?.role
  const isSuperAdmin = (role?.slug || role?.name || '').toUpperCase().includes('SUPER_ADMIN')

  const [form, setForm] = useState<Partial<SmsSettingsType> & { api_key?: string }>({})
  const [templates, setTemplates] = useState<Record<string, SmsTemplate>>({})
  const [msgType, setMsgType] = useState<string>('birthday')
  const [testPhone, setTestPhone] = useState('')
  const [logPage, setLogPage] = useState(1)
  const { data: logs, isLoading: logsLoading } = useGetSmsLogs(logPage)

  // Hydrate the form once settings load
  useEffect(() => {
    if (data?.settings) {
      const s = data.settings
      setForm({
        enabled: s.enabled,
        driver: s.driver,
        sender_id: s.sender_id,
        api_username: s.api_username ?? '',
      })
      if (s.templates) setTemplates(s.templates)
    }
  }, [data])

  const set = (patch: Partial<SmsSettingsType> & { api_key?: string }) =>
    setForm((prev) => ({ ...prev, ...patch }))

  const cur: SmsTemplate | undefined = templates[msgType]
  const setTpl = (patch: Partial<SmsTemplate>) =>
    setTemplates((prev) => ({ ...prev, [msgType]: { ...prev[msgType], ...patch } }))

  // Only the editable fields of each template are sent back.
  const templatesPayload = () =>
    Object.fromEntries(
      Object.values(templates).map((t) => [t.type, { enabled: t.enabled, message: t.message, time: t.time }])
    )

  const handleSave = () => {
    const payload: any = { templates: templatesPayload() }
    // Gateway fields are only editable by super admin.
    if (isSuperAdmin) {
      payload.enabled = form.enabled
      payload.driver = form.driver
      payload.sender_id = form.sender_id
      payload.api_username = form.api_username
      if (form.api_key) payload.api_key = form.api_key
    }
    updateMutation.mutate(payload)
  }

  const handleBroadcast = async () => {
    if (!cur) return
    if (!window.confirm(`Send this ${cur.label} to ALL patients now? This cannot be undone.`)) return
    // Save the latest message first so the broadcast uses what's on screen.
    await updateMutation.mutateAsync({ templates: templatesPayload() })
    broadcastMutation.mutate({ type: msgType })
  }

  const handleTest = () => {
    if (!testPhone.trim()) return
    testMutation.mutate({ phone: testPhone.trim() })
  }

  const logColumns = useMemo(
    () => [
      {
        title: 'Date',
        dataIndex: 'created_at',
        key: 'created_at',
        render: (d: string) => new Date(d).toLocaleString('en-GB'),
      },
      {
        title: 'Recipient',
        key: 'recipient',
        render: (_: any, r: any) => (
          <div className="flex flex-col">
            <span className="font-medium">{r.patient_name || '—'}</span>
            <span className="text-xs text-gray-500">{r.phone}</span>
          </div>
        ),
      },
      {
        title: 'Type',
        dataIndex: 'type',
        key: 'type',
        render: (t: string) => <Tag color={t === 'birthday' ? 'blue' : t === 'test' ? 'purple' : 'default'}>{t}</Tag>,
      },
      {
        title: 'Status',
        dataIndex: 'status',
        key: 'status',
        render: (s: string) => <Tag color={s === 'sent' ? 'green' : 'red'}>{s}</Tag>,
      },
      { title: 'Provider', dataIndex: 'provider', key: 'provider' },
      {
        title: 'Message / Error',
        key: 'detail',
        render: (_: any, r: any) => (
          <span className="text-xs text-gray-600">{r.error ? `⚠ ${r.error}` : r.message}</span>
        ),
      },
    ],
    []
  )

  if (isLoading) {
    return (
      <Layout>
        <div className="p-2.5 md:p-6">
          <h2 className="text-2xl md:text-[32px] font-bold text-[#030229] mb-6">SMS & Messaging</h2>
          <div className="rounded-[14px] bg-white p-6 animate-pulse h-64" />
        </div>
      </Layout>
    )
  }

  if (error) {
    return (
      <Layout>
        <div className="p-4 md:p-6 text-red-500">
          Failed to load SMS settings. You may not have permission to view this page.
        </div>
      </Layout>
    )
  }

  const stats = data?.stats
  const isAfricasTalking = form.driver === 'africastalking'

  return (
    <Layout>
      <div className="p-2.5 md:p-6">
        <h2 className="text-2xl md:text-[32px] font-bold text-[#030229] mb-2">SMS &amp; Messaging</h2>
        <p className="text-sm text-gray-500 mb-4 md:mb-6">
          Configure the SMS gateway and the messages sent to patients (announcements, birthdays,
          appointment reminders, and general notifications).
        </p>

        {/* Stats */}
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 md:gap-4 mb-4 md:mb-6">
          <div className="rounded-[14px] bg-white p-4">
            <div className="text-gray-500 text-sm">Total sent</div>
            <div className="text-2xl font-bold">{stats?.sent_total ?? 0}</div>
          </div>
          <div className="rounded-[14px] bg-white p-4">
            <div className="text-gray-500 text-sm">Birthday messages sent</div>
            <div className="text-2xl font-bold">{stats?.birthday_sent_total ?? 0}</div>
          </div>
          <div className="rounded-[14px] bg-white p-4">
            <div className="text-gray-500 text-sm">Failed</div>
            <div className="text-2xl font-bold text-red-500">{stats?.failed_total ?? 0}</div>
          </div>
        </div>

        {/* Gateway config — provider credentials, super admin only */}
        {isSuperAdmin && (
          <Card title="SMS Gateway" description="Choose your provider and enter the sending credentials.">
            <div className="flex items-center justify-between mb-5 p-3 rounded-lg bg-[#F5F6FA]">
              <div>
                <div className="font-medium">Enable SMS sending</div>
                <div className="text-xs text-gray-500">Master switch — when off, no SMS (including birthdays) is sent.</div>
              </div>
              <Switch checked={!!form.enabled} onChange={(v) => set({ enabled: v })} />
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-5">
              <Field label="Provider">
                <Select
                  value={form.driver}
                  onChange={(v) => set({ driver: v })}
                  options={(data?.settings.drivers || []).map((d) => ({ value: d, label: DRIVER_LABELS[d] || d }))}
                />
              </Field>
              <Field label="Sender ID" hint="The name recipients see as the sender (max 11 chars for most routes).">
                <Input value={form.sender_id} onChange={(e) => set({ sender_id: e.target.value })} placeholder="Shalom" />
              </Field>
              {isAfricasTalking && (
                <Field label="API Username" hint="Africa's Talking application username.">
                  <Input
                    value={form.api_username ?? ''}
                    onChange={(e) => set({ api_username: e.target.value })}
                    placeholder="e.g. sandbox or your app username"
                  />
                </Field>
              )}
              <Field
                label="API Key"
                hint={
                  data?.settings.api_key_set
                    ? `A key is saved (${data.settings.api_key_masked}). Leave blank to keep it.`
                    : 'Enter your provider API key.'
                }
              >
                <Input.Password
                  value={form.api_key ?? ''}
                  onChange={(e) => set({ api_key: e.target.value })}
                  placeholder={data?.settings.api_key_set ? '•••••••• (unchanged)' : 'Enter API key'}
                  autoComplete="new-password"
                />
              </Field>
            </div>
          </Card>
        )}

        {/* Configure messages */}
        <Card
          title="Message Configuration"
          description="Choose a message type, set its content, and configure how it is sent."
        >
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-5 mb-4">
            <Field label="Message type">
              <Select
                value={msgType}
                onChange={(v) => setMsgType(v)}
                options={MESSAGE_TYPE_ORDER.filter((t) => templates[t]).map((t) => ({
                  value: t,
                  label: templates[t].label,
                }))}
              />
            </Field>
            <Field label="Send to (audience)" hint="Determined by the message type.">
              <Input value={cur?.audience_label ?? ''} readOnly className="bg-[#F5F6FA]" />
            </Field>
          </div>

          {cur && (
            <>
              {/* Scheduled types (birthday, appointment reminder): enable + send time */}
              {cur.scheduled ? (
                <>
                  <div className="flex items-center justify-between mb-4 p-3 rounded-lg bg-[#F5F6FA]">
                    <div>
                      <div className="font-medium">Send automatically</div>
                      <div className="text-xs text-gray-500">
                        Runs daily at the time below (Africa/Lagos) for the audience above.
                      </div>
                    </div>
                    <Switch checked={!!cur.enabled} onChange={(v) => setTpl({ enabled: v })} />
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-5 mb-4">
                    <Field label="Daily send time" hint="24-hour time in Africa/Lagos.">
                      <Input
                        type="time"
                        value={cur.time ?? '06:30'}
                        onChange={(e) => setTpl({ time: e.target.value })}
                      />
                    </Field>
                  </div>
                </>
              ) : (
                <div className="mb-4 p-3 rounded-lg bg-[#FFF7E6] border border-[#FFE7BA] text-sm text-[#8c6d1f]">
                  This is a one-off broadcast — it is sent to <b>all patients</b> when you click
                  <b> Send to all patients</b> below (it is not scheduled).
                </div>
              )}

              <Field
                label={`${cur.label} content`}
                hint={
                  msgType === 'appointment_reminder'
                    ? 'Placeholders: {first_name}, {last_name}, {name}, {appointment_date}, {appointment_time}.'
                    : 'Placeholders: {first_name}, {last_name}, {name} are replaced with the patient’s name.'
                }
              >
                <TextArea
                  rows={4}
                  maxLength={1000}
                  showCount
                  value={cur.message}
                  placeholder={`Enter the ${cur.label.toLowerCase()} message…`}
                  onChange={(e) => setTpl({ message: e.target.value })}
                />
              </Field>
            </>
          )}
        </Card>

        {/* Save + Broadcast */}
        <div className="flex flex-col sm:flex-row justify-end gap-3 mb-6">
          {cur && !cur.scheduled && (
            <Button
              danger
              size="large"
              onClick={handleBroadcast}
              disabled={broadcastMutation.isLoading || updateMutation.isLoading || !cur.message?.trim()}
            >
              {broadcastMutation.isLoading ? <LoadingOutlined spin /> : 'Send to all patients now'}
            </Button>
          )}
          <Button
            type="primary"
            size="large"
            onClick={handleSave}
            disabled={updateMutation.isLoading}
            style={{ background: '#0061FF' }}
          >
            {updateMutation.isLoading ? <LoadingOutlined spin /> : 'Save Changes'}
          </Button>
        </div>

        {/* Test SMS */}
        <Card title="Send a test SMS" description="Verify your gateway configuration by sending a message to any number.">
          <div className="flex flex-col sm:flex-row gap-3">
            <Input
              value={testPhone}
              onChange={(e) => setTestPhone(e.target.value)}
              placeholder="e.g. 08031234567"
              className="sm:max-w-xs"
            />
            <Button onClick={handleTest} disabled={testMutation.isLoading || !testPhone.trim()}>
              {testMutation.isLoading ? <LoadingOutlined spin /> : 'Send test'}
            </Button>
          </div>
        </Card>

        {/* Activity log */}
        <Card title="SMS Activity Log" description="Recent messages sent by the system.">
          <div className="overflow-x-auto">
            <Table
              rowKey="id"
              columns={logColumns as any}
              dataSource={logs?.data || []}
              loading={logsLoading}
              pagination={false}
              size="small"
              scroll={{ x: 'max-content' }}
            />
          </div>
          <div className="flex justify-end mt-4">
            <Pagination
              current={logs?.current_page || 1}
              total={logs?.total || 0}
              pageSize={logs?.per_page || 15}
              onChange={setLogPage}
              size="small"
              showSizeChanger={false}
            />
          </div>
        </Card>
      </div>
    </Layout>
  )
}

export default SmsSettingsPage
