"use client"

import { useState } from "react"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Upload, CheckCircle2, AlertCircle, HelpCircle, FileSpreadsheet } from "lucide-react"

interface MatchResult {
  bankRow: {
    date: string
    description: string
    amount: number
    reference: string
  }
  pledgeId: string | null
  pledgeReference: string | null
  confidence: "exact" | "partial" | "amount_only" | "none"
  matchedAmount: number
  autoConfirmed: boolean
}

export default function ReconcilePage() {
  const [file, setFile] = useState<File | null>(null)
  const [uploading, setUploading] = useState(false)
  const [results, setResults] = useState<{
    summary: {
      totalRows: number
      credits: number
      exactMatches: number
      partialMatches: number
      unmatched: number
      autoConfirmed: number
    }
    matches: MatchResult[]
  } | null>(null)

  const [mapping, setMapping] = useState({
    dateCol: "Date",
    descriptionCol: "Description",
    creditCol: "Credit",
    referenceCol: "Reference",
  })

  const handleUpload = async () => {
    if (!file) return
    setUploading(true)
    try {
      const formData = new FormData()
      formData.append("file", file)
      formData.append("mapping", JSON.stringify(mapping))

      const res = await fetch("/api/imports/bank-statement", {
        method: "POST",
        headers: { "x-org-id": "demo" },
        body: formData,
      })
      const data = await res.json()
      if (data.summary) {
        setResults(data)
      }
    } catch {
      // handle error
    }
    setUploading(false)
  }

  const confidenceIcon = (c: string) => {
    switch (c) {
      case "exact": return <CheckCircle2 className="h-4 w-4 text-success-green" />
      case "partial": return <AlertCircle className="h-4 w-4 text-warm-amber" />
      default: return <HelpCircle className="h-4 w-4 text-muted-foreground" />
    }
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-extrabold text-gray-900">Reconcile Payments</h1>
        <p className="text-muted-foreground mt-1">Upload a bank statement CSV to automatically match payments to pledges</p>
      </div>

      {/* Upload card */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <FileSpreadsheet className="h-5 w-5" /> Bank Statement Import
          </CardTitle>
          <CardDescription>
            Export your bank statement as CSV and upload it here. We&apos;ll match payment references automatically.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Column mapping */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="space-y-1">
              <Label className="text-xs">Date Column</Label>
              <Input
                value={mapping.dateCol}
                onChange={(e) => setMapping((m) => ({ ...m, dateCol: e.target.value }))}
                className="h-9 text-sm"
              />
            </div>
            <div className="space-y-1">
              <Label className="text-xs">Description Column</Label>
              <Input
                value={mapping.descriptionCol}
                onChange={(e) => setMapping((m) => ({ ...m, descriptionCol: e.target.value }))}
                className="h-9 text-sm"
              />
            </div>
            <div className="space-y-1">
              <Label className="text-xs">Credit/Amount Column</Label>
              <Input
                value={mapping.creditCol}
                onChange={(e) => setMapping((m) => ({ ...m, creditCol: e.target.value }))}
                className="h-9 text-sm"
              />
            </div>
            <div className="space-y-1">
              <Label className="text-xs">Reference Column</Label>
              <Input
                value={mapping.referenceCol}
                onChange={(e) => setMapping((m) => ({ ...m, referenceCol: e.target.value }))}
                className="h-9 text-sm"
              />
            </div>
          </div>

          {/* File upload */}
          <div className="border-2 border-dashed border-gray-200 rounded-2xl p-8 text-center hover:border-trust-blue/50 transition-colors">
            <Upload className="h-10 w-10 text-muted-foreground mx-auto mb-3" />
            <input
              type="file"
              accept=".csv"
              onChange={(e) => setFile(e.target.files?.[0] || null)}
              className="hidden"
              id="csv-upload"
            />
            <label htmlFor="csv-upload" className="cursor-pointer">
              <p className="font-medium">{file ? file.name : "Click to upload CSV"}</p>
              <p className="text-xs text-muted-foreground mt-1">CSV file from your bank</p>
            </label>
          </div>

          <Button onClick={handleUpload} disabled={!file || uploading} className="w-full">
            {uploading ? "Processing..." : "Upload & Match"}
          </Button>
        </CardContent>
      </Card>

      {/* Results */}
      {results && (
        <>
          {/* Summary */}
          <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
            <Card>
              <CardContent className="pt-6 text-center">
                <p className="text-2xl font-bold">{results.summary.totalRows}</p>
                <p className="text-xs text-muted-foreground">Total Rows</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-6 text-center">
                <p className="text-2xl font-bold">{results.summary.credits}</p>
                <p className="text-xs text-muted-foreground">Credits</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-6 text-center">
                <p className="text-2xl font-bold text-success-green">{results.summary.exactMatches}</p>
                <p className="text-xs text-muted-foreground">Exact Matches</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-6 text-center">
                <p className="text-2xl font-bold text-warm-amber">{results.summary.partialMatches}</p>
                <p className="text-xs text-muted-foreground">Partial</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-6 text-center">
                <p className="text-2xl font-bold text-success-green">{results.summary.autoConfirmed}</p>
                <p className="text-xs text-muted-foreground">Auto-confirmed</p>
              </CardContent>
            </Card>
          </div>

          {/* Match table */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Match Results</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b text-left">
                      <th className="pb-3 font-medium text-muted-foreground">Confidence</th>
                      <th className="pb-3 font-medium text-muted-foreground">Date</th>
                      <th className="pb-3 font-medium text-muted-foreground">Description</th>
                      <th className="pb-3 font-medium text-muted-foreground">Amount</th>
                      <th className="pb-3 font-medium text-muted-foreground">Matched Pledge</th>
                      <th className="pb-3 font-medium text-muted-foreground">Status</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {results.matches.map((m, i) => (
                      <tr key={i} className="hover:bg-gray-50/50">
                        <td className="py-3">{confidenceIcon(m.confidence)}</td>
                        <td className="py-3">{m.bankRow.date}</td>
                        <td className="py-3 max-w-[200px] truncate">{m.bankRow.description}</td>
                        <td className="py-3 font-bold">£{m.matchedAmount.toFixed(2)}</td>
                        <td className="py-3 font-mono">{m.pledgeReference || "—"}</td>
                        <td className="py-3">
                          {m.autoConfirmed ? (
                            <Badge variant="success">Auto-confirmed</Badge>
                          ) : m.confidence === "partial" ? (
                            <Badge variant="warning">Review needed</Badge>
                          ) : m.confidence === "none" ? (
                            <Badge variant="outline">No match</Badge>
                          ) : (
                            <Badge variant="success">Matched</Badge>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </>
      )}
    </div>
  )
}
