'use client'
import { useState, useCallback, useRef } from 'react'
import Papa from 'papaparse'
import Box from '@mui/material/Box'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Chip from '@mui/material/Chip'
import Alert from '@mui/material/Alert'
import AlertTitle from '@mui/material/AlertTitle'
import LinearProgress from '@mui/material/LinearProgress'
import Table from '@mui/material/Table'
import TableHead from '@mui/material/TableHead'
import TableBody from '@mui/material/TableBody'
import TableRow from '@mui/material/TableRow'
import TableCell from '@mui/material/TableCell'
import Select from '@mui/material/Select'
import MenuItem from '@mui/material/MenuItem'
import TextField from '@mui/material/TextField'
import Collapse from '@mui/material/Collapse'
import { useT } from '@/contexts/LangContext'
import {
  TABS3_CLIENT_MAP, TABS3_MATTER_MAP,
  LEGALTREK_CLIENT_MAP, LEGALTREK_MATTER_MAP,
  LEXRING_CLIENT_MAP, LEXRING_MATTER_MAP,
  type SoiClientField, type SoiMatterField,
} from './fieldMaps'

// ── Types ─────────────────────────────────────────────────────────────────────

type Source = 'tabs3' | 'legaltrek' | 'lexring'

interface ParsedFile {
  headers: string[]
  rows:    Record<string, string>[]
  name:    string
}

interface FieldMapping {
  [soiField: string]: string   // soiField → detected source column (or '' = unmapped)
}

interface ImportResult {
  clientsImported: number
  clientsSkipped:  number
  mattersImported: number
  mattersSkipped:  number
  errors:          string[]
  warnings:        string[]
}

// ── Auto-detect column mapping ────────────────────────────────────────────────

function autoMap(
  headers: string[],
  fieldMap: Record<string, string[]>,
): FieldMapping {
  const result: FieldMapping = {}
  const normalised = headers.map(h => h.toLowerCase().trim().replace(/\s+/g, '_'))

  for (const [soiField, candidates] of Object.entries(fieldMap)) {
    const match = candidates.find(c =>
      normalised.some(h => h === c.toLowerCase().replace(/\s+/g, '_')),
    )
    result[soiField] = match
      ? headers[normalised.indexOf(match.toLowerCase().replace(/\s+/g, '_'))] ?? ''
      : ''
  }
  return result
}

function applyMapping(rows: Record<string, string>[], mapping: FieldMapping): Record<string, string>[] {
  return rows.map(row => {
    const out: Record<string, string> = {}
    for (const [soiField, sourceCol] of Object.entries(mapping)) {
      if (sourceCol && row[sourceCol] !== undefined) {
        out[soiField] = row[sourceCol] ?? ''
      }
    }
    return out
  })
}

// ── File drop zone ────────────────────────────────────────────────────────────

function DropZone({
  label, sublabel, changeLabel, rowsLabel, onParsed, file,
}: {
  label: string
  sublabel: string
  changeLabel: string
  rowsLabel: (rows: number, cols: number) => string
  onParsed: (f: ParsedFile) => void
  file: ParsedFile | null
}) {
  const inputRef = useRef<HTMLInputElement>(null)
  const [dragging, setDragging] = useState(false)

  const parse = useCallback((f: File) => {
    Papa.parse(f, {
      header: true, skipEmptyLines: true,
      complete: (result) => {
        onParsed({
          name:    f.name,
          headers: result.meta.fields ?? [],
          rows:    result.data as Record<string, string>[],
        })
      },
    })
  }, [onParsed])

  const onDrop = (e: React.DragEvent) => {
    e.preventDefault(); setDragging(false)
    const f = e.dataTransfer.files[0]
    if (f) parse(f)
  }

  return (
    <Box
      onClick={() => inputRef.current?.click()}
      onDragOver={e => { e.preventDefault(); setDragging(true) }}
      onDragLeave={() => setDragging(false)}
      onDrop={onDrop}
      sx={{
        border: '2px dashed',
        borderColor: file ? '#0D9394' : dragging ? '#0D9394' : 'divider',
        borderRadius: 2, p: 3, cursor: 'pointer', textAlign: 'center',
        bgcolor: file ? 'rgba(13,147,148,0.04)' : dragging ? 'rgba(13,147,148,0.06)' : 'transparent',
        transition: 'all 0.2s',
        '&:hover': { borderColor: '#0D9394', bgcolor: 'rgba(13,147,148,0.04)' },
      }}
    >
      <input ref={inputRef} type='file' accept='.csv,.txt' hidden
        onChange={e => { if (e.target.files?.[0]) parse(e.target.files[0]) }} />
      {file ? (
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 1 }}>
          <i className='ri-file-excel-line' style={{ color: '#0D9394', fontSize: '1.4rem' }} />
          <Box sx={{ textAlign: 'left' }}>
            <Typography variant='body2' sx={{ fontWeight: 700, color: '#0D9394' }}>{file.name}</Typography>
            <Typography variant='caption' color='text.secondary'>{rowsLabel(file.rows.length, file.headers.length)}</Typography>
          </Box>
          <Chip label={changeLabel} size='small' sx={{ ml: 1 }} />
        </Box>
      ) : (
        <Box>
          <i className='ri-upload-cloud-line' style={{ fontSize: '2rem', color: 'rgba(150,150,150,0.6)' }} />
          <Typography variant='body2' sx={{ fontWeight: 600, mt: 0.5 }}>{label}</Typography>
          <Typography variant='caption' color='text.secondary'>{sublabel}</Typography>
        </Box>
      )}
    </Box>
  )
}

// ── Mapping editor ────────────────────────────────────────────────────────────

const REQUIRED_CLIENT: SoiClientField[] = ['externalId', 'companyName']
const REQUIRED_MATTER: SoiMatterField[] = ['externalClientId', 'title']

function MappingTable<F extends string>({
  fieldLabels, mapping, headers, required, onChange, colSoiField, colSourceColumn, colStatus, skipLabel,
}: {
  fieldLabels: Record<F, string>
  mapping: FieldMapping
  headers: string[]
  required: F[]
  onChange: (field: F, col: string) => void
  colSoiField: string
  colSourceColumn: string
  colStatus: string
  skipLabel: string
}) {
  return (
    <Table size='small'>
      <TableHead>
        <TableRow>
          <TableCell sx={{ fontWeight: 700, width: '40%' }}>{colSoiField}</TableCell>
          <TableCell sx={{ fontWeight: 700 }}>{colSourceColumn}</TableCell>
          <TableCell sx={{ fontWeight: 700, width: 80 }}>{colStatus}</TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        {(Object.entries(fieldLabels) as [F, string][]).map(([field, label]) => {
          const mapped = mapping[field] ?? ''
          const isReq = required.includes(field)
          const ok = !!mapped
          return (
            <TableRow key={field} sx={{ '&:hover': { bgcolor: 'action.hover' } }}>
              <TableCell>
                <Typography variant='body2' sx={{ fontWeight: isReq ? 700 : 400 }}>
                  {label}
                  {isReq && <span style={{ color: '#FF3E1D', marginLeft: 3 }}>*</span>}
                </Typography>
              </TableCell>
              <TableCell>
                <Select size='small' value={mapped} displayEmpty fullWidth
                  onChange={e => onChange(field, e.target.value)}
                  sx={{ fontSize: '0.825rem' }}>
                  <MenuItem value=''><em style={{ color: '#aaa' }}>{skipLabel}</em></MenuItem>
                  {headers.map(h => (
                    <MenuItem key={h} value={h} sx={{ fontSize: '0.825rem' }}>{h}</MenuItem>
                  ))}
                </Select>
              </TableCell>
              <TableCell>
                {ok
                  ? <i className='ri-checkbox-circle-fill' style={{ color: '#0D9394', fontSize: '1.1rem' }} />
                  : isReq
                    ? <i className='ri-error-warning-fill' style={{ color: '#FF3E1D', fontSize: '1.1rem' }} />
                    : <i className='ri-subtract-line' style={{ color: '#ccc', fontSize: '1.1rem' }} />
                }
              </TableCell>
            </TableRow>
          )
        })}
      </TableBody>
    </Table>
  )
}

// ── Main view ─────────────────────────────────────────────────────────────────

export default function MigrateView() {
  const t = useT()
  const [source, setSource]     = useState<Source>('tabs3')
  const [clientFile, setClientFile] = useState<ParsedFile | null>(null)
  const [matterFile, setMatterFile] = useState<ParsedFile | null>(null)
  const [clientMap, setClientMap]   = useState<FieldMapping>({})
  const [matterMap, setMatterMap]   = useState<FieldMapping>({})
  const [attorney, setAttorney]     = useState('')
  const [importing, setImporting]   = useState(false)
  const [result, setResult]         = useState<ImportResult | null>(null)
  const [showMappings, setShowMappings] = useState(false)

  const clientFieldMap = source === 'tabs3' ? TABS3_CLIENT_MAP : source === 'legaltrek' ? LEGALTREK_CLIENT_MAP : LEXRING_CLIENT_MAP
  const matterFieldMap = source === 'tabs3' ? TABS3_MATTER_MAP : source === 'legaltrek' ? LEGALTREK_MATTER_MAP : LEXRING_MATTER_MAP

  const CLIENT_FIELD_LABELS: Record<SoiClientField, string> = {
    externalId:          t.migrate.cfExternalId,
    clientType:          t.migrate.cfClientType,
    firstName:           t.migrate.cfFirstName,
    lastName:            t.migrate.cfLastName,
    companyName:         t.migrate.cfCompanyName,
    email:               t.migrate.cfEmail,
    phone:               t.migrate.cfPhone,
    address:             t.migrate.cfAddress,
    nationality:         t.migrate.cfNationality,
    passportNumber:      t.migrate.cfPassportNumber,
    responsibleAttorney: t.migrate.cfResponsibleAttorney,
    originatingAttorney: t.migrate.cfOriginatingAttorney,
    status:              t.migrate.cfStatus,
    engagementDate:      t.migrate.cfEngagementDate,
    notes:               t.migrate.cfNotes,
  }

  const MATTER_FIELD_LABELS: Record<SoiMatterField, string> = {
    externalClientId:    t.migrate.mfExternalClientId,
    externalMatterId:    t.migrate.mfExternalMatterId,
    title:               t.migrate.mfTitle,
    practiceArea:        t.migrate.mfPracticeArea,
    subType:             t.migrate.mfSubType,
    status:              t.migrate.mfStatus,
    responsibleAttorney: t.migrate.mfResponsibleAttorney,
    openedAt:            t.migrate.mfOpenedAt,
    closedAt:            t.migrate.mfClosedAt,
    notes:               t.migrate.mfNotes,
  }

  const handleClientFile = (f: ParsedFile) => {
    setClientFile(f)
    setClientMap(autoMap(f.headers, clientFieldMap))
    setResult(null)
  }

  const handleMatterFile = (f: ParsedFile) => {
    setMatterFile(f)
    setMatterMap(autoMap(f.headers, matterFieldMap))
    setResult(null)
  }

  const switchSource = (s: Source) => {
    setSource(s)
    setClientFile(null); setMatterFile(null)
    setClientMap({}); setMatterMap({})
    setResult(null)
  }

  const readyToImport = !!clientFile && !!attorney.trim()

  const runImport = async () => {
    if (!clientFile) return
    setImporting(true)
    setResult(null)

    const clients = applyMapping(clientFile.rows, clientMap)
    const matters = matterFile ? applyMapping(matterFile.rows, matterMap) : []

    try {
      const res = await fetch('/api/migrate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ source, clients, matters, defaultAttorney: attorney.trim() }),
      })
      setResult(await res.json())
    } catch {
      setResult({ clientsImported: 0, clientsSkipped: 0, mattersImported: 0, mattersSkipped: 0, errors: [t.migrate.networkError], warnings: [] })
    } finally {
      setImporting(false)
    }
  }

  const sourceLabel = source === 'tabs3' ? 'TABS3' : source === 'legaltrek' ? 'LegalTrek' : 'LexRing'

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>

      {/* Header */}
      <Box sx={{ background: 'linear-gradient(135deg, #0D9394 0%, #096B6C 100%)', borderRadius: 3, p: 4, color: '#fff' }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, mb: 1 }}>
          <i className='ri-arrow-left-right-line' style={{ fontSize: '1.6rem' }} />
          <Typography variant='h4' sx={{ fontWeight: 700, color: '#fff' }}>{t.migrate.title}</Typography>
        </Box>
        <Typography variant='body1' sx={{ color: 'rgba(255,255,255,0.85)', maxWidth: 560 }}>
          {t.migrate.subtitle}
        </Typography>
      </Box>

      {/* Source selector */}
      <Card>
        <CardContent sx={{ pb: '16px !important' }}>
          <Typography variant='overline' color='text.secondary' sx={{ mb: 1.5, display: 'block' }}>
            {t.migrate.sourceSystem}
          </Typography>
          <Box sx={{ display: 'flex', gap: 2 }}>
            {(['tabs3', 'legaltrek', 'lexring'] as Source[]).map(s => {
              const label = s === 'tabs3' ? 'TABS3' : s === 'legaltrek' ? 'LegalTrek' : 'LexRing'
              const desc  = s === 'tabs3' ? t.migrate.srcTabs3Desc : s === 'legaltrek' ? t.migrate.srcLegalTrekDesc : t.migrate.srcLexRingDesc
              return (
                <Box key={s} onClick={() => switchSource(s)} sx={{
                  flex: 1, border: '2px solid', cursor: 'pointer', borderRadius: 2, p: 2.5,
                  borderColor: source === s ? '#0D9394' : 'divider',
                  bgcolor: source === s ? 'rgba(13,147,148,0.05)' : 'transparent',
                  transition: 'all 0.2s',
                }}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
                    <i className='ri-database-2-line'
                      style={{ fontSize: '1.4rem', color: source === s ? '#0D9394' : '#aaa' }} />
                    <Box>
                      <Typography variant='body2' sx={{ fontWeight: 700, color: source === s ? '#0D9394' : 'text.primary' }}>
                        {label}
                      </Typography>
                      <Typography variant='caption' color='text.secondary'>
                        {desc}
                      </Typography>
                    </Box>
                  </Box>
                </Box>
              )
            })}
          </Box>
        </CardContent>
      </Card>

      {/* Upload */}
      <Card>
        <CardContent>
          <Typography variant='h6' sx={{ fontWeight: 700, mb: 0.5 }}>{t.migrate.uploadTitle}</Typography>
          <Typography variant='body2' color='text.secondary' sx={{ mb: 2.5 }}>
            {t.migrate.uploadSubtitle(sourceLabel)}
          </Typography>

          <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 2, mb: 2.5 }}>
            <Box>
              <Typography variant='caption' sx={{ fontWeight: 700, mb: 0.75, display: 'block', color: 'text.secondary', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                {t.migrate.clientsLabel} <span style={{ color: '#FF3E1D' }}>*</span>
              </Typography>
              <DropZone
                label={t.migrate.dropClient}
                sublabel={source === 'tabs3' ? t.migrate.clientPathTabs3 : source === 'legaltrek' ? t.migrate.clientPathLegalTrek : t.migrate.clientPathLexRing}
                changeLabel={t.migrate.changeFile}
                rowsLabel={t.migrate.rowsInfo}
                onParsed={handleClientFile}
                file={clientFile}
              />
            </Box>
            <Box>
              <Typography variant='caption' sx={{ fontWeight: 700, mb: 0.75, display: 'block', color: 'text.secondary', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                {t.migrate.mattersLabel} <span style={{ color: '#aaa', fontWeight: 400 }}>{t.migrate.mattersOptional}</span>
              </Typography>
              <DropZone
                label={t.migrate.dropMatter}
                sublabel={source === 'tabs3' ? t.migrate.matterPathTabs3 : source === 'legaltrek' ? t.migrate.matterPathLegalTrek : t.migrate.matterPathLexRing}
                changeLabel={t.migrate.changeFile}
                rowsLabel={t.migrate.rowsInfo}
                onParsed={handleMatterFile}
                file={matterFile}
              />
            </Box>
          </Box>

          {/* Default attorney */}
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <TextField
              label={t.migrate.defaultAttorneyLabel}
              size='small'
              value={attorney}
              onChange={e => setAttorney(e.target.value)}
              placeholder='e.g. Patchara S.'
              helperText={t.migrate.defaultAttorneyHint}
              sx={{ width: 340 }}
            />
          </Box>
        </CardContent>
      </Card>

      {/* Column mappings */}
      {(clientFile || matterFile) && (
        <Card>
          <CardContent sx={{ pb: '8px !important' }}>
            <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1 }}>
              <Box>
                <Typography variant='h6' sx={{ fontWeight: 700 }}>{t.migrate.mappingTitle}</Typography>
                <Typography variant='body2' color='text.secondary'>
                  {t.migrate.mappingSubtitle(sourceLabel)}
                </Typography>
              </Box>
              <Button size='small' variant='text' onClick={() => setShowMappings(v => !v)}
                endIcon={<i className={showMappings ? 'ri-arrow-up-s-line' : 'ri-arrow-down-s-line'} />}>
                {showMappings ? t.migrate.mappingHide : t.migrate.mappingReview}
              </Button>
            </Box>

            <Collapse in={showMappings}>
              <Box sx={{ display: 'grid', gridTemplateColumns: clientFile && matterFile ? '1fr 1fr' : '1fr', gap: 3, mt: 1.5, pb: 1 }}>
                {clientFile && (
                  <Box>
                    <Typography variant='caption' sx={{ fontWeight: 700, mb: 1, display: 'block', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                      {t.migrate.clientRows(clientFile.rows.length)}
                    </Typography>
                    <MappingTable
                      fieldLabels={CLIENT_FIELD_LABELS}
                      mapping={clientMap}
                      headers={clientFile.headers}
                      required={REQUIRED_CLIENT}
                      onChange={(f, col) => setClientMap(m => ({ ...m, [f]: col }))}
                      colSoiField={t.migrate.colSoiField}
                      colSourceColumn={t.migrate.colSourceColumn}
                      colStatus={t.migrate.colStatus}
                      skipLabel={t.migrate.skipColumn}
                    />
                  </Box>
                )}
                {matterFile && (
                  <Box>
                    <Typography variant='caption' sx={{ fontWeight: 700, mb: 1, display: 'block', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                      {t.migrate.matterRows(matterFile.rows.length)}
                    </Typography>
                    <MappingTable
                      fieldLabels={MATTER_FIELD_LABELS}
                      mapping={matterMap}
                      headers={matterFile.headers}
                      required={REQUIRED_MATTER}
                      onChange={(f, col) => setMatterMap(m => ({ ...m, [f]: col }))}
                      colSoiField={t.migrate.colSoiField}
                      colSourceColumn={t.migrate.colSourceColumn}
                      colStatus={t.migrate.colStatus}
                      skipLabel={t.migrate.skipColumn}
                    />
                  </Box>
                )}
              </Box>
            </Collapse>

            {/* Mapping summary chips */}
            {!showMappings && clientFile && (
              <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', mt: 0.5, pb: 1 }}>
                {Object.entries(clientMap).filter(([, v]) => v).map(([k, v]) => (
                  <Chip key={k} size='small' label={`${CLIENT_FIELD_LABELS[k as SoiClientField] ?? k} → ${v}`}
                    icon={<i className='ri-checkbox-circle-fill' style={{ color: '#0D9394', fontSize: '0.85rem' }} />}
                    sx={{ fontSize: '0.72rem' }} />
                ))}
              </Box>
            )}
          </CardContent>
        </Card>
      )}

      {/* Import button + progress */}
      {clientFile && (
        <Card>
          <CardContent>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <Box sx={{ flex: 1 }}>
                <Typography variant='body2' sx={{ fontWeight: 600 }}>
                  {t.migrate.readyTitle(clientFile.rows.length, matterFile ? matterFile.rows.length : null)}
                </Typography>
                <Typography variant='caption' color='text.secondary'>
                  {t.migrate.readyHint}
                </Typography>
              </Box>
              <Button
                variant='contained'
                size='large'
                disabled={!readyToImport || importing}
                onClick={runImport}
                startIcon={<i className={importing ? 'ri-loader-4-line' : 'ri-arrow-left-right-line'} />}
                sx={{ minWidth: 160 }}
              >
                {importing ? t.migrate.importing : t.migrate.importBtn(sourceLabel)}
              </Button>
            </Box>
            {importing && <LinearProgress sx={{ mt: 2, borderRadius: 1 }} />}
          </CardContent>
        </Card>
      )}

      {/* Results */}
      {result && (
        <Card>
          <CardContent>
            <Typography variant='h6' sx={{ fontWeight: 700, mb: 2 }}>{t.migrate.resultTitle}</Typography>

            <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 2, mb: 2 }}>
              {[
                { label: t.migrate.clientsImported, value: result.clientsImported, color: '#0D9394' },
                { label: t.migrate.clientsSkipped,  value: result.clientsSkipped,  color: '#FF9F43' },
                { label: t.migrate.mattersImported, value: result.mattersImported, color: '#0D9394' },
                { label: t.migrate.mattersSkipped,  value: result.mattersSkipped,  color: '#FF9F43' },
              ].map(s => (
                <Box key={s.label} sx={{ textAlign: 'center', p: 1.5, bgcolor: 'action.hover', borderRadius: 2 }}>
                  <Typography variant='h4' sx={{ fontWeight: 800, color: s.value > 0 ? s.color : 'text.disabled' }}>
                    {s.value}
                  </Typography>
                  <Typography variant='caption' color='text.secondary'>{s.label}</Typography>
                </Box>
              ))}
            </Box>

            {result.errors.length > 0 && (
              <Alert severity='error' sx={{ mb: 1.5 }}>
                <AlertTitle>{t.migrate.errTitle(result.errors.length)}</AlertTitle>
                {result.errors.map((e, i) => <div key={i}>{e}</div>)}
              </Alert>
            )}
            {result.warnings.length > 0 && (
              <Alert severity='warning'>
                <AlertTitle>{t.migrate.warnTitle(result.warnings.length)}</AlertTitle>
                {result.warnings.slice(0, 10).map((w, i) => <div key={i}>{w}</div>)}
                {result.warnings.length > 10 && (
                  <div>{t.migrate.warnMore(result.warnings.length - 10)}</div>
                )}
              </Alert>
            )}
            {result.errors.length === 0 && result.warnings.length === 0 && (
              <Alert severity='success'>{t.migrate.allSuccess}</Alert>
            )}
          </CardContent>
        </Card>
      )}

    </Box>
  )
}
